iOS - 在UITextField外部触摸时关闭键盘 [英] iOS - Dismiss keyboard when touching outside of UITextField

查看:423
本文介绍了iOS - 在UITextField外部触摸时关闭键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当用户触摸 UITextField 之外时如何使键盘消失。

I'm wondering how to make the keyboard disappear when the user touches outside of a UITextField.

推荐答案

您需要添加 UITapGestureRecogniser 并将其分配给视图,然后在<$ c $上调用resign first responder c> UITextField 在它的选择器上。

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];

在dismissKeyboard中:

-(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)

对于dismissKeyboard

func dismissKeyboard (_ sender: UITapGestureRecognizer) {
    aTextField.resignFirstResponder()
}

这篇关于iOS - 在UITextField外部触摸时关闭键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆