どうも、ちょげ(@chogetarou)です。
TextFieldのの選択状態を操作する方法を紹介します。
方法

TextFieldの選択状態を操作するには、FocusStateプロパティを使います。
まず、FocusStateプロパティの値を用意します。
@FocusState var selectState : Bool
次に、選択状態を操作するTextFieldにfocusedモディファイアを付与します。
そして、focusedモディファイアの第1引数に変数のバインド、第2引数「equals」にtrueを指定します。
TextField("", text: $text)
.focused($selectState, equals : true)
あとは、FocusStateの変数を選択する際にはtrue、選択しない場合はfalseにします。
これでTextFieldの選択状態を操作することができます。
使用例
以下は、使用例です。
struct ContentView: View {
@FocusState var selectState: Bool
@State var text = ""
var body: some View {
VStack {
TextField("Your Text Here", text: $text)
.focused($selectState, equals : true)
.padding()
Button("Select") {
selectState = true
}
.padding()
Button("Unselect") {
selectState = false
}
}
}
}
コメント