首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITableView 點擊無響應?用錯了 didDeselectRowAtIndexPath,應用 didSelectRowAtIndexPath

     編輯:程式設計綜合問答

問題現象

實現了 tableView:didDeselectRowAtIndexPath:,第一次點擊 Cell 無反應,點擊第二個 Cell 時第一個才觸發邏輯。

根因

方法名搞錯了:

  • didSelectRowAtIndexPath:**選中**行時調用(點擊即觸發)。
  • didDeselectRowAtIndexPath:**取消選中**行時調用(需先有選中行,再點擊其他行才觸發前一行的取消選中)。

第一次點擊無「已選中行」,故 didDeselect 不觸發;點第二行時,第一行取消選中 → 觸發 didDeselect,看起來像「延遲一拍」。

修正

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 取消高亮
    // 你的跳轉邏輯...
    switch (indexPath.row) {
        case 0: ...
        case 1: ...
    }
}

補充最佳實踐

  • **務必調用 deselectRowAtIndexPath:animated:**,否則 Cell 長期高亮體驗極差。
  • 跳轉控制器建議提取方法,避免 switch 膨脹:[self navigateToModuleAtIndex:indexPath.row];
  • 若需「取消選中時執行邏輯」(極少見),才用 didDeselectRowAtIndexPath。

總結

**點擊 Cell 響應 = didSelectRowAtIndexPath**。didDeselect 是「失去焦點」回調。一字之差,行為天壤之別。新手必踩坑,記住即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved