您的位置:首页 > 产品设计 > UI/UE

UITextField的键盘的回收

2015-11-18 22:52 489 查看
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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uitextfield uiview