UITextField的键盘的回收

来源:互联网 发布:数据库的优化方法 编辑:程序博客网 时间:2024/06/05 01:49

UITextField的键盘的回收是取消UITextField的响应状态。
1、添加辅助视图
2、实现UITextField的代理方法
添加辅助视图:

// 创建辅助视图UIView *recoverKeyBoardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,CGRectGetWidth(self.window.frame) , 15)];// 为辅助视图添加回收键盘的按钮UIButton *recoverKeyBoardBtn = [UIButton buttonWithType:UIButtonTypeSystem];// 为回收键盘按钮设置位置大小[recoverKeyBoardBtn setFrame:CGRectMake(150, 0, 100, 10)];// 为回收键盘按钮添加title[recoverKeyBoardBtn setTitle:@"回收键盘" forState:UIControlStateNormal];// 为添加辅助视图按钮添加点击事件[recoverKeyBoardBtn addTarget:self action:@selector(recoverKeyBoard) forControlEvents:UIControlEventTouchUpInside];// 将添加辅助视图按钮添加到辅助视图上[recoverKeyBoardView addSubview:recoverKeyBoardBtn];// 创建文本输入框,并设置位置大小UITextField *textField = [[UITextField          alloc]initWithFrame:CGRectMake(150, 55, 110, 20)];// 设置文本框的边框样式textField.borderStyle = UITextBorderStyleRoundedRect;// 设置占位字符串textField.placeholder = @"需要输入的提示文字";// 为文本框设置tag值textField.tag = 1001;// 为textField添加辅助视图textField.inputAccessoryView = recoverKeyBoardView;// 回收键盘方法- (void)recoverKeyBoard{    // 根据tag值取出对应textField    UITextField *textField = (UITextField *)[self.window viewWithTag:1002];    // 将textField响应状态取消    [textField resignFirstResponder];}

实现UITextField的代理方法

// 加入UITextFieldDelegate协议@interface AppDelegate ()<UITextFieldDelegate>// 创建文本输入框,并设置位置大小UITextField *textField = [[UITextField          alloc]initWithFrame:CGRectMake(150, 55, 110, 20)];// 设置文本框的边框样式textField.borderStyle = UITextBorderStyleRoundedRect;// 设置占位字符串textField.placeholder = @"需要输入的提示文字";// 将UITextFieldDelegate协议委托给本身textField.delegate = self;// 点击键盘的return按钮时候调用- (BOOL)textFieldShouldReturn:(UITextField *)textField{    // 将文本框的响应状态取消    [textField resignFirstResponder];     return YES;}

这两种方法都可以实现键盘的收回。
经过这两天学习,我发现了一种点击屏幕空白地方回收键盘的方法:
首先创建一个轻拍手势并添加到本视图上

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

创建一个方法取消这个视图上的第一响应者状态

- (void)tapAction:(UITapGestureRecognizer *)sender{    UIView *view = sender.view;    [view endEditing:YES];}
0 0