iOS Swift中如何通过编程方式强制收起键盘?
Absolutely! You can definitely programmatically force the keyboard to dismiss in iOS Swift, and there are a few straightforward ways to do it depending on your needs:
1. Force dismiss any active keyboard using endEditing(_:)
This is the most common approach, especially for your tap gesture scenario. Calling endEditing(true) on your view will tell any first responder (like your UITextField or UITextView) to resign, regardless of whether it wants to or not.
Here's how to complete your dismissKeyboard method properly:
@objc func dismissKeyboard(sender: Any) { // Passing true forces the keyboard to dismiss immediately self.view.endEditing(true) }
This works perfectly for your tap gesture because it will dismiss the keyboard no matter which text field/text view was active.
2. Resign first responder for a specific text field/text view
If you want to target a specific input element (for example, after the user finishes typing in a particular field), you can call resignFirstResponder() directly on that element.
Suppose you have outlets for your text fields like this:
@IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var messageTextView: UITextView!
You can dismiss the keyboard for just one of them like so:
// Dismiss keyboard from the text field firstNameTextField.resignFirstResponder() // Or dismiss from the text view messageTextView.resignFirstResponder()
This is useful if you only want to dismiss the keyboard for a specific input, not all of them.
3. Catch-all dismissal using UIApplication
Another way to dismiss any active keyboard across your app is using the UIApplication shared instance to send a resign action to all responders:
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
This method will find whichever responder is currently the first responder and tell it to resign, making it a great catch-all if you need to dismiss the keyboard from anywhere in your code.
Key Notes:
endEditing(true)is the simplest and most reliable method for general dismissal (like your tap gesture).resignFirstResponder()is ideal when you need precise control over which input element to target.- All these methods work for both UITextField and UITextView since they both conform to
UIResponder.
内容的提问来源于stack exchange,提问作者David J

