如果用户点击屏幕键盘,我该如何解除键盘? [英] How can I dismiss the keyboard if a user taps off the on-screen keyboard?

查看:109
本文介绍了如果用户点击屏幕键盘,我该如何解除键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击键盘外的任何地方时,我希望能够关闭iPhone键盘。我该怎么做呢?我知道我需要解雇响应者,但需要知道当用户敲出键盘空间时如何实现它。

I want to be able to dismiss the iPhone keyboard when the user taps anywhere outside of the keyboard. How can I go about doing this? I know I need to dismiss the responder, but need to know how to implement it when a user taps out of the keyboard space.

推荐答案

您需要添加 UITapGestureRecogniser 并将其分配给视图,然后在其选择器的文本字段上调用resign first responder。

You'll need to add an UITapGestureRecogniser and assign it to the view, and then call resign first responder on the textfield 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)

选项2

如果您无法承担添加gestureRecognizer的费用,那么您可以尝试这个

If you can't afford to add a gestureRecognizer then you can try this

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch * touch = [touches anyObject];
    if(touch.phase == UITouchPhaseBegan) {
        [aTextField resignFirstResponder];
    }
}

这篇关于如果用户点击屏幕键盘,我该如何解除键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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