LoginSignup
3
3

More than 3 years have passed since last update.

[SwiftUI]TextFieldでFirstResponderでキーボードを非表示にする方法とtextFieldStyleによるサイズや色の変更方法

Last updated at Posted at 2020-09-07

今回実装するもの

ダウンロード.gif

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

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3