键盘回收的几种方法

用弹出键盘和收回键盘举例子

第一种

AppDelegate.h声明协议 UITextFieldDelegate

AppDelegate.m

UITextField *t1 = [[UITextField alloc]initWithFrame:CGRectMake(50, 50, 200, 40)];

    t1.borderStyle = UITextBorderStyleRoundedRect;

    t1.backgroundColor = [UIColor yellowColor];

    [self.window addSubview:t1];

   

    // 设置代理,才能执行代理

    t1.delegate = self;

   

// 点击键盘上的return键

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

  // 解除第一响应者,键盘回收

 

    [textField resignFirstResponder];

 

    return YES;

}   

   第二种

//这里加了一个touchesBegan事件。点击屏幕任意处收回键盘

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    [self.view endEditing:YES];

}

 第三种 

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

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

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

3、编写隐藏代码:

- (IBAction)touchView:(id)sender {  

     [self.view endEditing:YES];  

}  

原文地址:https://www.cnblogs.com/Coder-GT/p/4866323.html