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


当前回答

添加这个扩展到你的ViewController:

  extension UIViewController {
// Ends editing view when touches to view 
  open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
    self.view.endEditing(true)
  }
}

其他回答

您还可以添加一个点击手势识别器来重新使用键盘。: D

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let recognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
    backgroundView.addGestureRecognizer(recognizer)
}
    func handleTap(recognizer: UITapGestureRecognizer) {
    textField.resignFirstResponder()
    textFieldtwo.resignFirstResponder()
    textFieldthree.resignFirstResponder()

    println("tappped")
}
override func viewDidLoad() {
    super.viewDidLoad()
          
    //Looks for single or multiple taps. 
     let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))

    //Uncomment the line below if you want the tap not not interfere and cancel other interactions.
    //tap.cancelsTouchesInView = false 

    view.addGestureRecognizer(tap)
}

//Calls this function when the tap is recognized.
@objc func dismissKeyboard() {
    //Causes the view (or one of its embedded text fields) to resign the first responder status.
    view.endEditing(true)
}

如果你打算在多个uiviewcontroller中使用这个功能,这里有另一种方法来完成这个任务:

// Put this piece of code anywhere you like
extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false            
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

现在在每个UIViewController中,你要做的就是调用这个函数:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

这个函数是我的repo中包含的标准函数,它包含了很多有用的Swift扩展,比如这个,看看:https://github.com/goktugyil/EZSwiftExtensions

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

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

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

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

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

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

加上这两行:

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

当视图中有多个文本字段时

为了遵循@modocache的建议避免调用view. enditing(),您可以跟踪成为第一响应器的文本字段,但这很混乱且容易出错。

另一种方法是在视图控制器中的所有文本字段上调用resignFirstResponder()。下面是一个创建所有文本字段集合的示例(在我的情况下,验证代码无论如何都需要):

@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!

var allTextFields: Array<UITextField>!  // Forced unwrapping so it must be initialized in viewDidLoad
override func viewDidLoad()
{
    super.viewDidLoad()
    self.allTextFields = [self.firstName, self.lastName, self.email]
}

有了可用的集合,就可以简单地遍历所有这些集合:

private func dismissKeyboard()
{
    for textField in allTextFields
    {
        textField.resignFirstResponder()
    }
}

所以现在你可以在你的手势识别器(或任何适合你的地方)中调用遣散键盘()。缺点是在添加或删除字段时必须维护UITextFields列表。

欢迎评论。如果在不是第一响应者的控件上调用resignFirstResponder()有问题,或者如果有一种简单且保证无bug的方法来跟踪当前的第一响应者,我很乐意听到它!