swiftui dismiss keyboard in sheet code example
Example 1: how to dismiss keyboard swiftui
#if canImport(UIKit)
extension View {
func hideKeyboard() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
#endif
Example 2: how to dismiss keyboard swiftui
struct ContentView: View {
@State private var tipAmount = ""
var body: some View {
VStack {
TextField("Name: ", text: $tipAmount)
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.decimalPad)
Button("Submit") {
print("Tip: \(self.tipAmount)")
self.hideKeyboard()
}
}
}
}
Example 3: how to dismiss keyboard in swift
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}