2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SwiftUIのTextFieldのキーボードでreturnキーを選択するとキーボードを閉じる方法

Posted at

SwiftUIのTextFieldのキーボードがデフォルトだと閉じれなくて困りました。
専用の閉じるボタンを用意するのも面倒で、かつUIが増えるし、改行が必要ないならreturnキーで閉じたい。

とりあえずこれでできたので、同じ悩みを抱えている方は
是非コピペして動かしてみて下さい。

struct ContentView: View {
    @State private var inputText = ""
    @FocusState private var textField: Bool

    var body: some View {
        VStack {
            TextField("何か入力してね♪",text: Binding<String>(get: {
                inputText
            }, set: { value in
                // キーボードのreturnキー押下したらキーボードを閉じる.
                if value.contains("\n"){
                    textField = false
                } else {
                    inputText = value
                }
                
            }),axis: .vertical)
            .focused($textField)
        }
    }
}
2
3
0

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?