Home > Net >  SwiftUI: How to hide keyboard after using DatePicker
SwiftUI: How to hide keyboard after using DatePicker

Time:03-13

How can I hide keyboard after user picks some date in DatePicker?

Currently when I tap on the name TextField, and then - with keyboard shown up - I tap on DatePicker, the keyboards hides when DatePicker's popup window for choosing date appears, but after I pick some date in DatePicker's popup window, keyboard appears again.

How can I make it so that the keyboard does not appear again after value is submitted inside DatePicker's popup window?

import SwiftUI

struct EditView: View {
    @Binding var name: String
    @State private var birthday: Date = Date()
    
    @FocusState private var isTextFieldFocused
    
    var body: some View {
        Form {
            TextField("Name", text: $name)
                .focused($isTextFieldFocused)
            DatePicker("Birthday", selection: $birthday)
        }
    }
}

struct EditView_Previews: PreviewProvider {
    static var previews: some View {
        EditView(name: .constant(String("Joe")))
    }
}

CodePudding user response:

FocusState is not necessary and add an extension of view to hide your keyboard

struct EditView: View {
@Binding var name: String = ""
@State private var birthday: Date = Date()
//@FocusState private var isTextFieldFocused

        var body: some View {
            Form {
                TextField("Name", text: $name)
                DatePicker("Birthday", selection: $birthday)
            }
            .onTapGesture {
                hideKeyboard()
            }
        }
}
extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

enter image description here

  • Related