标签:
退出键盘
iOS开发中键盘的退出方法用很多中我们应该在合适的地方使用合适的方法才能更好的提高开发的效率和应用的性能
下面给大家介绍几种最常用的键盘退出方法,基本上iOS开发中的键盘退出方法都是这几种中的一种活着几种。
一:textView
1 //通过委托来实现放弃第一响应者 2 #pragma mark - UITextView Delegate Method 3 -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 4 { 5 if([text isEqualToString:@"\n"]) { 6 [textView resignFirstResponder]; 7 return NO; 8 } 9 return YES; 10 }
二:textFiled
1 //通过委托来实现放弃第一响应者 2 #pragma mark - UITextField Delegate Method 3 - (BOOL)textFieldShouldReturn:(UITextField *)textField 4 { 5 [textField resignFirstResponder]; 6 return YES; 7 }
三:触摸屏幕
1 //所有的界面都可以实现 2 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 3 { 4 [self.view endEditing:YES]; 5 }
四:ScrollView拖拽
1 -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 2 { 3 [self.view endEditing:YES]; 4 }
注:结合使用endEditing和resignFirstResponder
五:通知方式
注册与移除通知
1 -(void) viewWillAppear:(BOOL)animated { 2 3 //注册键盘出现通知 4 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidShow:) 5 name: UIKeyboardDidShowNotification object:nil]; 6 //注册键盘隐藏通知 7 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:) 8 name: UIKeyboardDidHideNotification object:nil]; 9 [super viewWillAppear:animated]; 10 } 11 12 13 -(void) viewWillDisappear:(BOOL)animated { 14 //解除键盘出现通知 15 [[NSNotificationCenter defaultCenter] removeObserver:self 16 name: UIKeyboardDidShowNotification object:nil]; 17 //解除键盘隐藏通知 18 [[NSNotificationCenter defaultCenter] removeObserver:self 19 name: UIKeyboardDidHideNotification object:nil]; 20 21 [super viewWillDisappear:animated]; 22 }
实现通知的方法:
1 -(void) keyboardDidShow: (NSNotification *)notif { 2 3 if (keyboardVisible) {//键盘已经出现要忽略通知 4 return; 5 } 6 // 获得键盘尺寸 7 NSDictionary* info = [notif userInfo]; 8 NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; 9 CGSize keyboardSize = [aValue CGRectValue].size; 10 11 //重新定义ScrollView的尺寸 12 CGRect viewFrame = self.scrollView.frame; 13 viewFrame.size.height -= (keyboardSize.height); 14 self.scrollView.frame = viewFrame; 15 16 //滚动到当前文本框 17 CGRect textFieldRect = [self.textField frame]; 18 [self.scrollView scrollRectToVisible:textFieldRect animated:YES]; 19 20 keyboardVisible = YES; 21 } 22 23 -(void) keyboardDidHide: (NSNotification *)notif { 24 25 NSDictionary* info = [notif userInfo]; 26 NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; 27 CGSize keyboardSize = [aValue CGRectValue].size; 28 29 CGRect viewFrame = self.scrollView.frame; 30 viewFrame.size.height += keyboardSize.height; 31 self.scrollView.frame = viewFrame; 32 33 if (!keyboardVisible) { 34 return; 35 } 36 37 keyboardVisible = NO; 38 39 }
标签:
原文地址:http://www.cnblogs.com/iCocos/p/4555743.html