問(wèn)題
之前做過(guò)好幾個(gè)項(xiàng)目,UITableViewCell嵌套著UITextField或者UITextView,當(dāng)彈起鍵盤(pán)時(shí)會(huì)遮擋編輯窗口,之前一直用改變UITableView的Frame方式,然后設(shè)置UITableView的ContentOffset方式滾動(dòng)到對(duì)應(yīng)的編輯位置,但是這種方式存在著不友好的UI交互。
解決思路
監(jiān)聽(tīng)鍵盤(pán)
UIKeyboardWillShowNotification 和 UIKeyboardWillHideNotification在鍵盤(pán)彈起的時(shí)候改變
UITableView的contentInset調(diào)用
UITableView的API- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;滾動(dòng)到指定的位置鍵盤(pán)彈下時(shí)同樣改變
UITableView的contentInset恢復(fù)到原來(lái)位置
代碼
[[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 *)notification {
NSDictionary *userInfo = [notification userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [value CGRectValue];
CGFloat height = keyboardRect.size.height;
NSNumber *durationTime = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:durationTime.floatValue + 0.1 animations:^{
} completion:^(BOOL finished) {
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
/**滾動(dòng)到指定的cell*/
[self.tableView scrollToRowAtIndexPath:self.selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}];
}
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
NSNumber *durationTime = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
[UIView animateWithDuration:durationTime.floatValue animations:^{
}completion:^(BOOL finished) {
UIEdgeInsets insets = self.tableView.contentInset;
insets.bottom = 0.0;
self.tableView.contentInset = insets;
}];
}