SwiftUI - Dismiss Keyboard when Picker selected
Asked Answered
C

1

1

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)

    }
}
Configurationism answered 31/10, 2019 at 12:37 Comment(0)
G
0

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()}
Goody answered 2/11, 2019 at 3:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.