今回実装するもの
Code
ContentView
struct ContentView: View {
@State private var text = ""
@State private var flag = false
var body: some View {
let textFlag = String(flag)
VStack {
TextField("サンプル", text: $text)
Text("\(textFlag)")
} .textFieldStyle(CustomTextFieldStyle())
.onTapGesture {
if flag {
UIApplication.shared.closeKeyboard()
}
flag.toggle()
}
}
}
struct CustomTextFieldStyle: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.padding(.horizontal,16)
.font(.system(size: 20))
.frame(width: UIScreen.main.bounds.width, height: 60)
.background(Color.secondary)
.cornerRadius(8)
.foregroundColor(.white)
}
}
extension UIApplication {
func closeKeyboard() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
解説
let textFlag = String(flag)によりキーボードの出し入れの様子を可視化しています。
またtapGestureによりUIApplication.shared.closeKeyboard()でキーボードを閉じています。
closeKeyboard()については
extension UIApplication {
func closeKeyboard() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
とする事でキーボードを閉じる事ができます。
またSwiftUIではtextFieldStyleにてTextFieldを装飾する事ができます。
おすすめは
.frame(width: UIScreen.main.bounds.width, height: 60)
の部分でwidth: UIScreen.main.bounds.width
にする事でどのデバイスでも綺麗に表示する事ができます。
最後に
普段は個人でSwiftUIでアプリを作っています。ハードも作るの大好きです。
よければ下記もチェックして下さい♪
Twitter
https://twitter.com/oka_yuuji
note
https://note.com/oka_yuuji