本文介绍了触摸整个应用程序时如何关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弹出键盘的不同视图控制器中有多个文本字段.

I have multiple textFields in different viewControllers where keyboard is popped up.

我知道当用户点击屏幕的不同部分时如何关闭键盘,但我不想将其硬编码到我应用的每个角落.

I know how to dismiss keyboard when user clicks on a different part of the screen but I don't want to go and hard code it into every corner of my app.

那么,当用户点击屏幕上除键盘之外的任何地方时,是否有办法强制键盘在应用的任何地方解除键盘?

So is there anyway to enforce keyboard getting keyboard dismissed everywhere on the app when the user clicks anywhere on the screen other than keyboard?

我想扩展 UIViewController,但我在视图中也有一些 textFields,我将其添加为子视图.也许我可以通过某种方式扩展 TextField 类本身?

I was thinking of extending the UIViewController, but I also have some textFields inside a view that I add as a subview. Perhaps there could be someway that I extend TextField class itself?

推荐答案

我建议创建一个 base UIViewController 并让你的每个 ViewController 继承它;覆盖其中的 touchesBegan 方法:

I suggest to create a base UIViewController and let each of your ViewControllers inherit it; override touchesBegan method in it:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    view.endEditing(true)
}

或者您可以覆盖 viewDidLoad - 在基础 ViewController 中 - 并向视图添加一个 UITapGestureRecognizer,如下所示:

OR you can override viewDidLoad -in the base ViewController- and add a UITapGestureRecognizer to the view, as follows:

override func viewDidLoad() {
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Base.endEditing))
    view.addGestureRecognizer(tapGesture)
}

func endEditing() {
    view.endEditing(true)
}

这篇关于触摸整个应用程序时如何关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:44