我一直在到处找这个,但我似乎找不到。我知道如何解雇使用Objective-C键盘,但我不知道如何使用Swift?有人知道吗?


当前回答

如何解散键盘时,你点击任何地方关闭它

 //Setup dismiss keyboard gesture
 let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

     view.addGestureRecognizer(tap)
 }
 //Calling this function when the tapped
 @objc func dismissKeyboard() {

    view.endEditing(true)
 }

其他回答

viewDidLoad()方法中只有一行代码:

view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))

斯威夫特3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

因为我编辑的@King-Wizard的回答被拒绝了,所以发布了一个新的答案。

让你的类成为UITextField的委托并重写touchesBegan。

斯威夫特4

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    //Called when 'return' key is pressed. Return false to keep the keyboard visible.
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        return true
    }

    // Called when the user clicks on the view (outside of UITextField).
    override func touchesBegan(touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

}

为了扩展Esqarrouth的答案,我总是使用以下方法来解除键盘,特别是如果我正在解除键盘的类没有view属性和/或不是UIView的子类。

UIApplication.shared.keyWindow?.endEditing(true)

并且,为了方便起见,下面是uiapplication类的扩展:

extension UIApplication {

    /// Dismisses the keyboard from the key window of the
    /// shared application instance.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open class func endEditing(_ force: Bool = false) {
        shared.endEditing(force)
    }

    /// Dismisses the keyboard from the key window of this 
    /// application instance.
    ///
    /// - Parameters:
    ///     - force: specify `true` to force first responder to resign.
    open func endEditing(_ force: Bool = false) {
        keyWindow?.endEditing(force)
    }

}

我已经使用IQKeyBoardManagerSwift键盘。它很容易使用。 只需添加pod 'IQKeyboardManagerSwift'

导入IQKeyboardManagerSwift并在AppDelegate中的didFinishLaunchingWithOptions上编写代码。

///add this line 
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.enable = true