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


当前回答

为了扩展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

在故事板:

选择TableView 在右边,选择属性检查器 在键盘部分-选择你想要的解散模式

我得到了你

override func viewDidLoad() {
    super.viewDidLoad() /*This ensures that our view loaded*/
    self.textField.delegate = self /*we select our text field that we want*/   
    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard")))
}

func dismissKeyboard(){ /*this is a void function*/
    textField.resignFirstResponder() /*This will dismiss our keyboard on tap*/
}

斯威夫特3:

扩展选择器作为参数,能够做额外的东西在解散函数和cancelsTouchesInView,以防止扭曲与触摸的其他元素的视图。

extension UIViewController {
    func hideKeyboardOnTap(_ selector: Selector) {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

用法:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}

我更喜欢这样一句话:

view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboardFromView:"))

只要把它放在override viewDidLoad函数中,不管你想让它发生在哪个子类UIViewController中,然后把下面的代码放在你的项目中的一个新的空文件中,名为“UIViewController+dismissKeyboard.swift”:

import UIKit

extension UIViewController {
    // This function is called when the tap is recognized
    func dismissKeyboardFromView(sender: UITapGestureRecognizer?) {
        let view = sender?.view
        view?.endEditing(true)
    }
}