小编典典

使用Swift触摸任意位置以关闭iOS键盘

swift

我一直在寻找这个,但是我似乎找不到。我知道如何使用来关闭键盘,Objective-C但是我不知道如何使用Swift?有人知道吗?


阅读 383

收藏
2020-07-07

共1个答案

小编典典

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 like
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)
    }
}

现在在每个中UIViewController,您所需要做的就是调用此函数:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround() 
}

此功能作为标准功能包含在我的存储库中,其中包含许多类似这样的有用的Swift扩展,请查看:https
:
//github.com/goktugyil/EZSwiftExtensions

2020-07-07