UITextField的键盘的回收

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];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值