Swift TextEditorのキーボードを表示するサンプル
環境
Swift version 5.2.3 (swift-5.2.3-RELEASE)
Ubuntu 20.04.2 LTS
構文
TextEditorのキーボードを表示するには、@FocusStateとfocused修飾子を使います。
作成方法
1.Bool型の@FocusStaeを定義します
@FocusState private var focusedField: Bool
2.TextEditorにfocused修飾子を付与し、引数に用意した変数の参照を指定します。
TextEditor(text: $text)
.focused($focusedField)
3.フォーカスを合わせたい時に変数の値を「true」にします。
self.focusedField = true
4.使用例
struct ContentView: View {
@State var text = ""
@FocusState private var focusedField: Bool
var body: some View {
VStack {
TextEditor(text: $text)
.frame(width: 250, height: 250)
.border(Color.red)
.focused($focusedField)
Button("Test") {
focusedField = true
}
}
}
}
struct ContentView: View {
@State var text = ""
@FocusState private var focusedField: Bool
var body: some View {
VStack {
TextEditor(text: $text)
.frame(width: 250, height: 250)
.border(Color.red)
.focused($focusedField)
Button("Test") {
focusedField = true
}
}
}
}
struct ContentView: View { @State var text = "" @FocusState private var focusedField: Bool var body: some View { VStack { TextEditor(text: $text) .frame(width: 250, height: 250) .border(Color.red) .focused($focusedField) Button("Test") { focusedField = true } } } }