SwiftUI 在点击 segmentedControl 时关闭键盘 [英] SwiftUI dismiss keyboard when tapping segmentedControl

查看:21
本文介绍了SwiftUI 在点击 segmentedControl 时关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a TextField in SwiftUI that needs to use a different keyboard depending on the value of a @State variable determined by a SegementedControl() picker.

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

How can I dismiss the keyboard (like send an endEditing event) when the user taps a different segment? I need to do this because I want to change the keyboard type and if the textField is the responder, the keyboard won't change.

我有这个扩展:

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

我可以做类似的事情

UIApplication.shared.endEditing()

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

But I don't know where or how to call this when the user taps a different segment.

我曾尝试在 Picker 上放置一个 tapGesture,并且键盘确实关闭了,但是 tap 不会传递到选择器,因此它不会改变.

I have tried putting a tapGesture on the Picker and the keyboard does dismiss, but the tap does not pass through to the picker so it does not change.

此处的代码片段:

@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 附加到调用 endEditing()Picker无论何时设置:

Attach a custom Binding to the Picker that calls endEditing() whenever it is set:

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())
}

这篇关于SwiftUI 在点击 segmentedControl 时关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆