IOS TextFiled与TextView 键盘的收起以及处理键盘遮挡
IOS TextFiled与TextView 键盘的收起以及处理键盘遮挡
在iOS开发中,UITextFiled和UITextView是很常见的两个控件,当我们设置好这两个控件后,点击文字输入区域,系统会自动弹出键盘,但是如何收起键盘、点击哪里收起键盘,以及在iPhone4中键盘弹出后遮挡输入框怎么办呢?
这篇文章将带领大家解决:
1》点击其他空白区域收起键盘
2》点击键盘右下角的键收起键盘
3》处理键盘遮挡问题
一,点击其他空白区域收起键盘
- (void)viewDidLoad { [super viewDidLoad]; [self setUpForDismissKeyboard]; }
#pragma mark - 回收任何空白区域键盘事件 - (void)setUpForDismissKeyboard { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; UITapGestureRecognizer *singleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAnywhereToDismissKeyboard:)]; NSOperationQueue *mainQuene =[NSOperationQueue mainQueue]; [nc addObserverForName:UIKeyboardWillShowNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){ [self.view addGestureRecognizer:singleTapGR]; }]; [nc addObserverForName:UIKeyboardWillHideNotification object:nil queue:mainQuene usingBlock:^(NSNotification *note){ [self.view removeGestureRecognizer:singleTapGR]; }]; } - (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer { //此method会将self.view里所有的subview的first responder都resign掉 [self.view endEditing:YES]; }
二,点击键盘右下角的键收起键盘
#pragma mark - TextView 代理方法 -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if ([text isEqualToString:@"\n"]) { [self.workLogTextView resignFirstResponder]; return NO; } return YES; }
注意:需要遵守textView/textFiled的代理。改代码是textView代理方法,若实际用到的是textFiled,只需调用textFiled的该类方法即可。
三,处理键盘遮挡问题
#pragma mark 键盘遮挡 - (BOOL)textViewShouldBeginEditing:(UITextView *)textView { if (self.userInfo.isPhone4) { CGFloat offset_y = 0.f; if (textView.tag == CALL_CONTENT_TEXTFIRLD) { offset_y = 100.f; } CGPoint point = self.BackScrollView.contentOffset; point = CGPointMake(point.x, offset_y); [UIView animateWithDuration:0.25 animations:^{ self.BackScrollView.contentOffset = point; }]; } return YES; } - (BOOL)textViewShouldEndEditing:(UITextView *)textView{ if (self.userInfo.isPhone4) { CGFloat offset_y = 0.f; if (textView.tag == CALL_CONTENT_TEXTFIRLD) { offset_y = 100.f; } CGPoint point = self.BackScrollView.contentOffset; point = CGPointMake(point.x, 0); [UIView animateWithDuration:0.25 animations:^{ self.BackScrollView.contentOffset = point; }]; } return YES; }
注意:需要遵守 UIScrollViewDelegate 和 textView/textFiled的代理。需要该页面的父视图是UIScrollView,才能保证弹出键盘时页面向上移动,收起键盘时页面向下移动。代码中的self.BackScrollView就是对应的父视图,使用时请替换掉。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
栏 目:iOS代码
下一篇:使用Xcode为iOS应用项目创建PCH文件的方法及应用示例
本文标题:IOS TextFiled与TextView 键盘的收起以及处理键盘遮挡
本文地址:http://www.codeinn.net/misctech/175562.html