使用Swift触摸任意位置以关闭iOS键盘
我一直在寻找这个,但是我似乎找不到。我知道如何使用来关闭键盘,Objective-C
但是我不知道如何使用Swift
?有人知道吗?
回答:
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 code 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
以上是 使用Swift触摸任意位置以关闭iOS键盘 的全部内容, 来源链接: utcz.com/qa/399189.html