解决Keyboard遮盖输入的几种办法
一般来说,键盘遮挡主要有这么几种情况,一个是遮住UITextView,还有就是遮住UITextField,一般来说,比较推荐在UIScrollView或者UITableView里加入textfield的控件。但是有时也许难免。。
在UITextView中
这个在苹果官方文档中的项目中给出了做法,首先是注册观察者监听UIKeyboardWillShow和WillHide事件
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; }
实现自定义的方法
- (void)keyboardWillShow:(NSNotification *)aNotification { NSDictionary *userInfo = [aNotification userInfo]; CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect newFrame = self.view.frame; newFrame.size.height -= keyboardRect.size.height; [UIView beginAnimations:@"ResizeTextView" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = newFrame; [UIView commitAnimations]; }
获取键盘显示的信息,然后根据信息对view的frame进行调整,然后WillHide方法就跟上面相同,只不过把高度新高度改成+= keyboardRect.size.height就可以了,最后,移除观察者:
- (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; }
在UIView中遮挡UITextField
大体来说,处理方法同上面类似,主要采取动画平移的方法,而且还能适应切换输入法,我上来定义了个成员来记住一开始UIView的位置,然后在动画的处理上稍微进行了处理。_viewRect = self.view.frame
- (void)keyboardWillShow:(NSNotification *)aNotification { NSDictionary *userInfo = [aNotification userInfo]; CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect oldFrame = _viewRect; [UIView beginAnimations:@"ResizeView" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y - keyboardRect.size.height + 20, oldFrame.size.width, oldFrame.size.height); [UIView commitAnimations]; }
- (void)keyboardWillHide:(NSNotification *)aNotification { NSDictionary *userInfo = [aNotification userInfo]; NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect newFrame = _viewRect; newFrame.origin.y += 20; [UIView beginAnimations:@"ResizeView" context:nil]; [UIView setAnimationDuration:animationDuration]; self.view.frame = newFrame; [UIView commitAnimations]; }
UITableView
UITableView则有些尴尬,因为可以不用代码就可以实现向上平移,但是有一个问题就是点击空白处不能让键盘消失,它也不能去响应UIControl,看了很多方法,但是貌似都或多或少有点问题,这里也请教一下大神们有什么建议。我的方法是从GitHub上找到了一个TPKeyboardAvoidingTableView,让自己的UITableView子类去继承它,就可以很轻松的实现点击消失键盘事件了,具体的源码可以去下载看一看。