问题描述
我正在开发一个具有UIViewController的项目,在视图控制器上,scrollview上有一个UIScrollView和UITextField.像这样: 一个>我正在尝试关闭键盘,然后在文本字段中键入一些文本并点按该文本字段外的任意位置后将其隐藏.我尝试了以下代码:
I'm working on a project that have a UIViewController, on the view controller there is a UIScrollView and a UITextField on the scrollview.like this:I'm trying to dismiss the keyboard and hide it after typing some text in the textfield and tap anywhere outside the textfield.I've tried the following code:
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self;
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
当我在滚动视图之外点击时,它对我有用,但是当我在滚动视图上点击时,什么也没有发生,并且键盘没有隐藏.
It works for me when I tap outside the scrollview, but when I tap on the scrollview nothing happens and the keyboard doesn't hide.
在文本字段外的任意位置点击任何地方,有什么方法可以关闭键盘?谢谢
Is there any way to dismiss the keyboard when tapping anywhere outside the textfield?thanks
推荐答案
为Swift 4编辑
添加了@objc
.尽管这不是提高性能的最佳选择,但是在找到更好的解决方案之前,这里的一个实例不应引起太多问题.
Added @objc
. While this isn't the best option for performance, one instance of it here shouldn't cause too many problems until there is a better solution.
经过修改,可在需要与GestureRecognizer背后的项目进行交互时进行修复.
感谢@Rao指出这一点.添加了tap.cancelsTouchesInView = false
.
Thanks @Rao for pointing this out. Added tap.cancelsTouchesInView = false
.
这应该有助于您拥有多个UITextView
或UITextField
This should help you with having multiple UITextView
or UITextField
创建视图控制器的扩展.与尝试使用.resignFirstResponder()
Create an extension of the view controller. This has worked much smoother for me and with less hassle than trying to use .resignFirstResponder()
extension UIViewController
{
func setupToHideKeyboardOnTapOnView()
{
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard()
{
view.endEditing(true)
}
}
在viewDidLoad中调用self.setupToHideKeyboardOnTapOnView()
Call self.setupToHideKeyboardOnTapOnView()
in the viewDidLoad
这篇关于触摸UITextField外部的任何地方时(快速)如何关闭键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!