iOS - 在 UITextField 之外触摸时关闭键盘 [英] iOS - Dismiss keyboard when touching outside of UITextField
本文介绍了iOS - 在 UITextField 之外触摸时关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在用户触摸 UITextField
外部时让键盘消失.
I'm wondering how to make the keyboard disappear when the user touches outside of a UITextField
.
推荐答案
您需要添加一个 UITapGestureRecogniser
并将其分配给视图,然后在 上调用 resign first responderUITextField
在它的选择器上.
You'll need to add an UITapGestureRecogniser
and assign it to the view, and then call resign first responder on the UITextField
on it's selector.
代码:
在 viewDidLoad
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
关闭键盘:
-(void)dismissKeyboard
{
[aTextField resignFirstResponder];
}
(其中aTextField
是负责键盘的文本框)
(Where aTextField
is the textfield that is responsible for the keyboard)
Swift 3 版本看起来像那样
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)
对于解雇键盘
@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
aTextField.resignFirstResponder()
}
这篇关于iOS - 在 UITextField 之外触摸时关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文