我在 SwiftUI 中有一个 TextField,需要根据 SegmentedControl() 选择器确定的 @State 变量的值使用不同的键盘。
当用户点击不同的段时,如何关闭键盘(例如发送 endEditing 事件)?我需要这样做,因为我想更改键盘类型,并且如果 textField 是响应者,则键盘不会更改。
我有这个扩展:
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
我可以做类似的事情
UIApplication.shared.endEditing()
但是当用户点击不同的分段时,我不知道在哪里或如何调用它。
我尝试在选择器上放置一个点击手势,键盘确实会关闭,但点击不会传递到选择器,因此它不会改变。
这里的代码片段:
@State private var type:String = "name"
。 。 .
Form {
Section(header: Text("Search Type")) {
Picker("", selection: $type) {
Text("By Name").tag("name")
Text("By AppId").tag("id")
}.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Enter search value")) {
TextField(self.searchPlaceHolder, text: $searchValue)
.keyboardType(self.type == "name" ? UIKeyboardType.alphabet : UIKeyboardType.numberPad)
}
}
最佳答案
将自定义Binding
附加到Picker
,每当设置时调用endEditing()
:
Section(header: Text("Search Type")) {
Picker("", selection: Binding(get: {
self.type
}, set: { (res) in
self.type = res
UIApplication.shared.endEditing()
})) {
Text("By Name").tag("name")
Text("By AppId").tag("id")
}.pickerStyle(SegmentedPickerStyle())
}
关于ios - 点击分段控制时 SwiftUI 关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349955/