iOS:UITableView鍵盤(pán)彈出定位到編輯位置

問(wèn)題

之前做過(guò)好幾個(gè)項(xiàng)目,UITableViewCell嵌套著UITextField或者UITextView,當(dāng)彈起鍵盤(pán)時(shí)會(huì)遮擋編輯窗口,之前一直用改變UITableViewFrame方式,然后設(shè)置UITableViewContentOffset方式滾動(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;
    }];
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容