萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS UITableView 鍵盤遮擋輸入框的完美解決方案

當 UITableView 作為表單容器時,底部 Cell 被系統鍵盤遮擋是經典痛點。本文提供一套基於通知監聽與精準滾動的通用解決方案。

核心思路

  1. 記錄正在編輯的 UITextField(textFieldDidBeginEditing:)。
  2. 監聽 UIKeyboardWillShowNotification / UIKeyboardWillHideNotification。
  3. 將目標 Cell 滾動到可視區域頂部(或鍵盤上方)。
  4. 鍵盤收起時恢復原位。

關鍵代碼實現

1. 記錄當前編輯字段

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.lastEditingTextField = textField;
}

2. 鍵盤彈出處理

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = keyboardEndFrame.size.height;
    
    // 將 UITextField 座標轉換到 tableView 坐標系
    CGPoint pointInTable = [self.tableView convertPoint:self.lastEditingTextField.center 
                                                fromView:self.lastEditingTextField.superview];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTable];
    
    // 滾動到頂部(或根據需求調整為鍵盤上方)
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionTop 
                                  animated:YES];
}

3. 鍵盤收起恢復

- (void)keyboardWillHide:(NSNotification *)notification {
    // 可選:滾動回原位或保持當前位置
    // [self.tableView setContentOffset:CGPointZero animated:YES];
}

進階優化:只滾動必要距離

計算 CGRectIntersection 判斷 Cell 是否真被遮擋,僅在必要時滾動,避免不必要的視覺跳動:

CGRect cellRect = [self.tableView rectForRowAtIndexPath:indexPath];
CGRect visibleRect = self.tableView.bounds;
visibleRect.size.height -= keyboardHeight; // 可視區縮減鍵盤高度

if (!CGRectContainsRect(visibleRect, cellRect)) {
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionTop 
                                  animated:YES];
}

現代替代方案

  • IQKeyboardManager:零代碼接入,自動處理所有場景。
  • TPKeyboardAvoiding:輕量級封裝,原理相同但 API 更簡潔。
  • iOS 10+ UITextField 的 inputAssistantItem 配合 UIKeyboardWillChangeFrameNotification 實現更精細控制。

掌握原理後,根據專案複雜度選擇手寫或引入成熟庫,才是成熟開發者的態度。

copyright © 萬盛學電腦網 all rights reserved