cell中有UITextView时,输入文字是需要将tableView向上移,基本的做法是,注册键盘变化的通知在通知的方法中做tableVIew的位置调整,
一,一般做法
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
NSLog(@"register");
}
- (void)keyboardWasShown:(NSNotification *)aNotification {
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
///将内边距进行调整
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
}
- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
}
今天做项目发现以上方法有一定缺陷,当tableView有多组的时候,有一组cell不跟着向上移动照成如下情况:
当键盘出现时,尾视图向上移动了但是这一组中的cell没有向上移动,这是什么原因,我至今没有搞清楚.
上述方法还会出现问题
解决办法找到了就是在键盘出现的通知方法中找到第一响应者(一般是:UITextField),判断它所在的cell是否显示在可见区域,如果没有则让tableVIew滑动至该cell全部可见:
#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note
{
CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//取得第一响应者
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView *activeField = [keyWindow performSelector:@selector(firstResponder)];
//使用了苹果的私有方法,将无法上传到App Store,下一篇介绍不使用该方法获取第一响应者
//除去键盘后的页面显示区域
CGRect aRect = self.view.frame;
aRect.size.height = aRect.size.height - keyBoardRect.size.height - 64;
///修改arect:
CGRect tableReact = self.tableView.frame;
float y = _tableView.contentOffset.y;
tableReact.origin.y += y;
tableReact.size.height -= keyBoardRect.size.height;
aRect = tableReact;
//判断cell底部是否在显示范围内
CGPoint cellBottomPoint = CGPointMake(0.0, activeField.superview.superview.frame.origin.y +activeField.superview.superview.frame.size.height);
if (!CGRectContainsPoint(aRect, cellBottomPoint) ) {
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
CGPoint scrollPoint = CGPointMake(0.0, cellBottomPoint.y-aRect.size.height -44);
[_tableView setContentOffset:scrollPoint animated:YES];
}
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note
{
[UIView animateWithDuration:.35 animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 45, 0);
}];
}
这样就完美解决了以上问题;