在許多彈出式選擇清單中,表格只允許使用者選取單一項目。選取後,文字或樣式會改變,並顯示勾選標記;當使用者改選另一列時,前一列必須恢復為未選取狀態。
這類需求通常會搭配一個私有變數 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。