0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】@FocusStateのvalueは明示的に書かなくても自動的にtrue/falseになる?

Posted at

疑問点

  • FocusStatetrueの状態で画面をタップした際にキーボードを非表示にする処理を実装していた際、親ViewのonTapGesture()の中で明示的にFocusStatefalseにすることでキーボードを非表示にできた。
  • .focused修飾子を付与したTextField等をタップしたら@FocusStateは自動的にtrueになっている印象がある。その逆も然り。
  • ん?FocusStateってTextFieldはタップすることで自動的にtruefalseを切り替えられるのなら、明示的にfocusstate = truefocusstate = falseを書かなくてもいいということ?

コード

// Component
TextEditor(text: /* 省略 */)
  .focused($isFocused)


// Parent
struct ParentView {
    @FocusState var isFocused: Bool
    var body: some View {
        VStack {
            Component(isFocused: isFocused)
        }
        .onTapGesture {
            isFocused = false
        }
    }
}

解説

  • ユーザーの操作に応じてバインドされたブール値を自動的に更新する一方で、その値をコードで直接設定することも可能。
  • これによって、フォーカスをプログラムから制御することもできるとのこと。

まとめ

・デフォルトではFocusStateは自動的に切り替える
・明示的に切り替えることもできる

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?