我正在寻找一种在SwiftUI的任意位置轻击/隐藏键盘的方法。在旧的Swift中,我可以轻松地向ViewController插入扩展,例如:
extension 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)
}
}
并在hideKeyboardWhenTappedAround()
中呼叫viewDidLoad()
先谢谢您
答案 0 :(得分:0)
您可以使用它,它应该可以工作!
func setupKeyboardDismissRecognizer(){
let tapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(searchingActivity.dismissKeyboard))
self.view.addGestureRecognizer(tapRecognizer)
}
@objc func dismissKeyboard()
{
view.endEditing(true)
searchTableView.isHidden = true
}
编辑
好吧,如果您需要使用UIViewController,则应在函数中使用扩展方法,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
self.setupHideKeyboardOnTap()
}
//and the keyboard will be dismissed even by tapping on the NavigationBar.
import UIKit
extension UIViewController {
/// Call this once to dismiss open keyboards by tapping anywhere in the view controller
func setupHideKeyboardOnTap() {
self.view.addGestureRecognizer(self.endEditingRecognizer())
self.navigationController?.navigationBar.addGestureRecognizer(self.endEditingRecognizer())
}
/// Dismisses the keyboard from self.view
private func endEditingRecognizer() -> UIGestureRecognizer {
let tap = UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))
tap.cancelsTouchesInView = false
return tap
}
}