Swift TextFieldのキーボードにツールバーを追加するサンプル

環境
Swift version 5.2.3 (swift-5.2.3-RELEASE)
Ubuntu 20.04.2 LTS

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
TextField(xxx)
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
xxx
}
}
TextField(xxx) .toolbar { ToolbarItemGroup(placement: .keyboard) { xxx } }
TextField(xxx)
    .toolbar {
        ToolbarItemGroup(placement: .keyboard) {
           xxx
        }
    }

toolbarのクロージャーにToolbarItemGroupを追加し、ToolbarItemGroupの引数「placement」に「.keyboard」を指定します。
TextFieldのキーボードにツールバーを追加するには、toolbar修飾子を使います。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
struct ContentView: View {
@State var editingText = ""
@FocusState var isInputActive: Bool
var body: some View {
VStack {
TextField("文字の入力", text: $editingText)
.padding()
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Button("キャンセル") {
self.isInputActive = false
}
}
}
}
}
}
struct ContentView: View { @State var editingText = "" @FocusState var isInputActive: Bool var body: some View { VStack { TextField("文字の入力", text: $editingText) .padding() .toolbar { ToolbarItemGroup(placement: .keyboard) { Button("キャンセル") { self.isInputActive = false } } } } } }
struct ContentView: View {
    
    @State var editingText = ""
    @FocusState var isInputActive: Bool
    
    var body: some View {
        VStack {
            TextField("文字の入力", text: $editingText)
                .padding()
                .toolbar {
                    ToolbarItemGroup(placement: .keyboard) {
                        Button("キャンセル") {
                            self.isInputActive = false
                        }
                    }
                }
        }
    }
}

 

Swift

Posted by arkgame