SwiftUI-选择Picker后关闭键盘 [英] SwiftUI - Dismiss Keyboard when Picker selected

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

问题描述

当诸如日期选择器之类的另一个控件变为活动状态时,是否有一种简单的方法来消除键盘或任何其他活动控件?反之亦然.

Is there a simple means of dismissing the keyboard or any other active control when another control such as a date picker becomes active? Or vice versa.

有一些解散键盘的解决方案,但也会禁止使用选择器.

There are some solutions for dismissing the keyboard, but which also disable the use of a picker.

除了onTapGesture之外,可能还有其他事件要使用.

Possibly there is an event other than onTapGesture to use.

以下是一些说明问题的示例代码.

Follows is some sample code that illustrates the problem.

struct TestView: View {

    @State private var firstname = ""
    @State private var surname = ""
    @State private var birthdate = Date()

    @State private var activeField: Int = 0



    var body: some View {
        Form {
            Section{
                TextField("Firstname", text: self.$firstname)
                TextField("Surname", text: self.$surname)

                TextField("Surname", text: self.$surname, onEditingChanged: { (editingChanged) in
                           if editingChanged {
                               print("TextField focused")
                           } else {
                               print("TextField focus removed")
                            self.endEditing()
                           }
                       })
            }

            Section(header: Text("Time: ")){

                DatePicker(selection: self.$birthdate, in: ...Date(), displayedComponents: .date) {
                    Text("Date of Birth")
                }
                .onTapGesture {
                   self.endEditing()
                }
                DatePicker(selection: self.$birthdate, in: ...Date(), displayedComponents: .hourAndMinute) {
                    Text("Date of Birth")
                }
            }
        }


    }

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

        let keyWindow = UIApplication.shared.connectedScenes
                               .filter({$0.activationState == .foregroundActive})
                               .map({$0 as? UIWindowScene})
                               .compactMap({$0})
                               .first?.windows
                               .filter({$0.isKeyWindow}).first
                       keyWindow?.endEditing(true)

    }
}

推荐答案

除了onTapGesture,您还可以添加onAppear.这样可以解决您的担忧

Besides onTapGesture, you can add onAppear. That solves your concerns

    DatePicker(selection: self.$birthdate, in: ...Date(), displayedComponents: .date) {

                    Text("Date of Birth")

            }
            .onAppear{self.endEditing()}
            .onTapGesture{self.endEditing()}

这篇关于SwiftUI-选择Picker后关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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