点击空白处回收键盘

第一种方法

[view endEditing:YES]  这个方法可以让整个view取消第一响应者,从而让所有控件的键盘隐藏。

第一种: 使用view的touchesBegan:触摸事件来实现对键盘的隐藏,当点击view的区域就会触发这个事件

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    [self.view endEditing:YES];

}

 

第二种方法

第二种:创建自定义的触摸手势来实现对键盘的隐藏:

_textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];

    _textField.center = CGPointMake(self.view.frame.size.width * 0.5, 300);

    _textField.borderStyle = UITextBorderStyleRoundedRect;

    _textField.placeholder = @"请输入点东西";

    _textField.keyboardType = UIKeyboardTypeDefault;

    [self.view addSubview:_textField];

    

    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(returnKey)];

    tapGR.cancelsTouchesInView = NO;//

    [self.view addGestureRecognizer:tapGR];

    

}

 

- (void)returnKey {

    [_textField resignFirstResponder];

}

 

第三种:修改xib中UIView的Custom class为UIControl,UIControl是一些常用控件如UIButton的父类,是UIView的派生类,实现了对触摸和下按的封装。

1、首先设置xib中得UIView的Custom class为UIControl


2、设置关系事件,将xib中得UIView拖到.h区中

设置好事件为Touch Up Inside

3、编写隐藏代码:

 

[html] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
    1. - (IBAction)touchView:(id)sender {  
    2.      [self.view endEditing:YES];  
    3. }  
原文地址:https://www.cnblogs.com/naizui/p/5211555.html