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


当前回答

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

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

其他回答

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

我更喜欢这样一句话:

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)
    }
}
  import UIKit

  class ItemViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet weak var nameTextField: UITextField!

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

    // Called when 'return' key pressed. return NO to ignore.

    func textFieldShouldReturn(textField: UITextField) -> Bool {

            textField.resignFirstResponder()
             return true
     }

 // Called when the user click on the view (outside the UITextField).

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

一个简单的方法是选择文本字段并使用方法enditing (true)

e.g

exampleTextField.endEditing(true)

另一种可能是在你可能需要触摸的所有视图下面添加一个没有内容的大按钮。 给它一个名为:

@IBAction func dismissKeyboardButton(sender: AnyObject) {
    view.endEditing(true)
}

对我来说,手势识别器的问题是,它也捕捉了我想通过tableViewCells接收的所有触摸。