SwiftUI - Dismiss Keyboard when Picker selected

对着背影说爱祢 提交于 2020-01-14 03:58:13

问题


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.

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)

    }
}

回答1:


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


来源:https://stackoverflow.com/questions/58643512/swiftui-dismiss-keyboard-when-picker-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!