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


当前回答

在Swift 4中,添加@objc:

在viewDidLoad中:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)

功能:

@objc func dismissKeyboard() {
  view.endEditing(true)
}

其他回答

以下是如何通过点击其他地方来消除键盘,使用Swift 5只需两行。

(我讨厌添加另一个答案,但由于这是谷歌上的顶级结果,我将帮助像我这样的新手。)

在你的ViewController.swift中,找到viewDidLoad()函数。

加上这两行:

let tap: UIGestureRecognizer = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
        
view.addGestureRecognizer(tap)

我没有看到它被提到过,但是NotificationCenter可以告诉你键盘何时打开和关闭。例如,如果你想改变cancelsTouchesInView或一起删除手势识别器,这可以被使用。

例子:

var dismissKeyboardGestureRecognizer = UITapGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()

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

    //Add Notifications
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name:UIResponder.keyboardDidShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name:UIResponder.keyboardDidHideNotification, object: nil)
}

@objc func keyboardDidShow() {
    dismissKeyboardGestureRecognizer.cancelsTouchesInView = true
    view.addGestureRecognizer(dismissKeyboardGestureRecognizer)
}

@objc func keyboardDidHide() {
    dismissKeyboardGestureRecognizer.cancelsTouchesInView = false
    view.removeGestureRecognizer(dismissKeyboardGestureRecognizer)
}

@objc func dismissKeyboard() {
    view.endEditing(true)
}

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

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

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

作为一个新手程序员,当人们给出更熟练和不必要的回答时,可能会感到困惑……你不需要做上面所示的任何复杂的事情!

这是最简单的选择……在这种情况下,你的键盘出现在响应文本字段-在你的触摸屏函数中,只需添加resignFirstResponder函数。如下所示-键盘将关闭,因为First Responder被释放(退出Responder链)…

override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
    MyTextField.resignFirstResponder()
}

因为我编辑的@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)
    }

}