您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:讓 UITableView 一次只選中一行

編輯:iOS 開發綜合

在許多彈出式選擇清單中,表格只允許使用者選取單一項目。選取後,文字或樣式會改變,並顯示勾選標記;當使用者改選另一列時,前一列必須恢復為未選取狀態。

實作重點

這類需求通常會搭配一個私有變數 lastIndexPath 來記錄目前選取列。每次 didSelectRowAtIndexPath 被觸發時,先比較新舊 index,再更新勾選狀態。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (lastIndexPath == nil) {
        lastIndexPath = indexPath;
    }

    if (![indexPath isEqual:lastIndexPath]) {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;

        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;

        lastIndexPath = indexPath;
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

注意事項

lastIndexPath 必須在頁面首次載入時初始化為 nil,否則第一次點擊可能會出現錯誤。另外,若資料來源會動態更新,也要記得同步清理選取狀態,避免殘留錯誤的 index。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved