SwiftUI dismiss keyboard when tapping segmentedControl
Attach a custom Binding
to the Picker
that calls endEditing()
whenever it is set:
Section(header: Text("Search Type")) {
Picker("", selection: Binding(get: {
self.type
}, set: { (res) in
self.type = res
UIApplication.shared.endEditing()
})) {
Text("By Name").tag("name")
Text("By AppId").tag("id")
}.pickerStyle(SegmentedPickerStyle())
}
Update since iOS 13 / iPadOS 13 was released.
Since there is now support for multiple windows in one app you need to loop through the UIWindows and end editing one-by-one.
UIApplication.shared.windows.forEach { $0.endEditing(false) }
SwiftUI 2.0
Now it can be done in more elegant way, with .onChange
(actually it can be attached to any view, but at TextField
looks appropriate, by intention)
TextField("Placeholder", text: $searchValue)
.keyboardType(self.type == "name" ? UIKeyboardType.alphabet : UIKeyboardType.numberPad)
.onChange(of: type) { _ in
UIApplication.shared.endEditing() // << here !!
}
SwiftUI 1.0+
There are much similar to above approaches
a) requires import Combine
...
TextField("Placeholder", text: $searchValue)
.keyboardType(self.type == "name" ? UIKeyboardType.alphabet : UIKeyboardType.numberPad)
.onChange(of: type) { _ in
UIApplication.shared.endEditing()
}
.onReceive(Just(type)) { _ in
UIApplication.shared.endEditing() // << here !!
}
b) ... and not
TextField("Placeholder", text: $searchValue)
.keyboardType(self.type == "name" ? UIKeyboardType.alphabet : UIKeyboardType.numberPad)
.onReceive([type].publisher) { _ in
UIApplication.shared.endEditing() // << here !!
}