在 UITableView 中,我們通常透過 delegate 的 didSelectRowAtIndexPath 來取得被點擊的行。但有時候(例如某個 cell 內的 text field 正在輸入、鍵盤即將彈出),我們需要在別的地方找出「目前哪個 cell 是第一回應者」,進而把它捲到不會被鍵盤遮擋的位置。這時候可以遍歷 dataSource 來定位。
以下程式示範了這個思路:先取得每個 section 的 cell 數量,再逐一檢查每個 cell 的 accessoryView 是否為正在輸入的 text field。
NSIndexPath *indexPathOfOwnerCell = nil;
// 取得每個 section 裡共有多少個 cell
NSInteger numberOfCells = [self.myTableView.dataSource
tableView:self.myTableView
numberOfRowsInSection:0];
NSLog(@"numberOfCells=%d", numberOfCells);
// 逐一走訪所有 cell,找出正在輸入的那一個
for (NSInteger counter = 0; counter < numberOfCells; counter++){
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:counter inSection:0];
UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
UITextField *textField = (UITextField *)cell.accessoryView;
if ([textField isKindOfClass:[UITextField class]] == NO){
continue;
}
if ([textField isFirstResponder]){
indexPathOfOwnerCell = indexPath;
NSLog(@"indexPath.section=%d", indexPath.section);
NSLog(@"indexPath.row=%d", indexPath.row);
break;
}
}
[UIView commitAnimations];
// 找到後,把該 cell 捲到畫面中央,避免被鍵盤遮住
if (indexPathOfOwnerCell != nil){
[self.myTableView scrollToRowAtIndexPath:indexPathOfOwnerCell
atScrollPosition:UITableViewScrollPositionMiddle
animated:YES];
}
核心邏輯是:透過 isFirstResponder 判斷哪個 text field 正在被編輯,找到對應的 indexPath 後,再呼叫 scrollToRowAtIndexPath 把它捲進可視區域。這個技巧在表單類型的畫面中特別實用。