隐藏键盘的N种方法
---Created by luo.h
显示键盘
[textField becomeFirstResponder];
隐藏键盘
@interface ViewController ()<UITextFieldDelegate> { UITextField *CSTextField; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CSTextField =[[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 30)]; CSTextField.borderStyle=UITextBorderStyleNone; CSTextField.tag=10001; CSTextField.delegate = self;//指定文本框的代理: [self.view addSubview:CSTextField]; }
#pragma mark---收键盘-----
方式一.点击Return的时候隐藏键盘(需设置TextField的delegate)
- (BOOL)textFieldShouldReturn:(UITextField *)textField { [CSTextField resignFirstResponder];//需指定文本框的代理 CSTextField.delegate = self; return YES; }
方式二.点击view其他区域隐藏键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //1.直接交出CSTextField的第一响应者的身份 [CSTextField resignFirstResponder]; //2.遍历所有子视图 查找UITextField控件并通知文本失去第一响应者状态 for (UIView *subVie in self.view.subviews) { if ([subVie isKindOfClass:[UITextField class]]) { [subVie resignFirstResponder]; } } //3.view结束编辑 [self.view endEditing:YES]; //4.keyWindow 结束编辑 [[[UIApplication sharedApplication] keyWindow] endEditing:YES]; //5.发送resignFirstResponder. [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil]; //6.设置textField的Tag [[self.view viewWithTag:10001] resignFirstResponder]; }
// Scroll 滑动隐藏 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { [self.view endEditing:YES]; }
scrollView.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag;(适用于TableView)
其他关于UITextField资料 ios7学习之路七(隐藏虚拟键盘,解决键盘挡住UITextField问题)
关于UITextView隐藏键盘
思路基本和UITextField一样
1.方法一
//1.(结束编辑) [self.view endEditing:YES]; OR [self.text endEditing:YES]; //2.(注销第一响应) [self.text resignFirstResponder];
2.方法二 (Return)
/** * 需设置textView的delegate */ -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"\n"]) { [textView resignFirstResponder]; return NO; } return YES; }
作者:SIBU iOS DEV
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.