UITextField的键盘的回收
2015-11-18 22:52
489 查看
UITextField的键盘的回收是取消UITextField的响应状态。
1、添加辅助视图
2、实现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]; }
相关文章推荐
- Swift社交应用文本输入优化汇总
- CALayer与UIView的关系
- UITextField常用delegate
- UIView的bounds和frame区别
- uiview
- uiview生命周期
- UIView翻译 (参考)
- iOS 转变UIView到UIImage
- UIView动画
- UITextField
- iOS开发1:UITextField控件属性
- [Swift]UIKit学习之UITextField的用法
- IOS开发Swift语言UITextField设置靠左的间距
- IOS开发Swift语言键盘遮挡输入框(UITextField)
- initWithFrame 和 initWithCoder
- [CS193P] 第六堂課摘要及心得筆記
- UI第一天
- cocos2d-x 一些有用的函数
- 棋盘
- ios实现button变换颜色并可以放大、缩小、旋转