问题
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