override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "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)}如果要多次使用此功能,这是另一种执行此任务的方法
UIViewControllers:
// Put this piece of pre anywhere you likeextension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = 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() }此功能作为标准功能包含在我的存储库中,其中包含许多类似这样的有用的Swift扩展,请查看:https
:
//github.com/goktugyil/EZSwiftExtensions



