SwiftUI 在点击 segmentedControl 时关闭键盘

Ste*_*nch 9 ios resignfirstresponder swiftui

我在 SwiftUI 中有一个 TextField,它需要使用不同的键盘,具体取决于由 SegementedControl() 选择器确定的 @State 变量的值。

当用户点击不同的段时,如何关闭键盘(如发送 endEditing 事件)?我需要这样做是因为我想更改键盘类型,如果 textField 是响应者,则键盘不会改变。

我有这个扩展:

extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以做类似的事情

UIApplication.shared.endEditing()
Run Code Online (Sandbox Code Playgroud)

但是当用户点击不同的段时,我不知道在哪里或如何调用它。

我试过在 Picker 上放置一个 tapGesture 并且键盘确实关闭了,但是点击不会传递到选择器,所以它不会改变。

代码片段在这里:

@State private var type:String = "name"
Run Code Online (Sandbox Code Playgroud)

. . .

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

自 iOS 13 / iPadOS 13 发布以来的更新。

由于现在在一个应用程序中支持多个窗口,因此您需要循环遍历 UIWindows 并逐一结束编辑。

UIApplication.shared.windows.forEach { $0.endEditing(false) }
Run Code Online (Sandbox Code Playgroud)


RPa*_*l99 5

将自定义附加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())
}
Run Code Online (Sandbox Code Playgroud)