You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift中如何通过编程方式强制收起键盘?

How to Programmatically Dismiss the Keyboard in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:03:50