これについてあちこち探し回ったのですが、見つからないようです。 を使用してキーボードを閉じる方法は知っていますObjective-C
が、 を使用してそれを実行する方法がわかりませんSwift
。誰か知っていますか?
ベストアンサー1
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)
}
この機能を複数で使用する場合は、このタスクを実行する別の方法がありますUIViewControllers
。
// 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()
}
この関数は私のリポジトリに標準関数として含まれています。このリポジトリには、次のような便利な Swift 拡張機能が多数含まれています。ぜひチェックしてみてください。https://github.com/goktugyil/EZSwiftExtensions