實作 collectionView:didDeselectItemAtIndexPath: 切換 Cell 圖片,點擊第一個 Cell 無反應,點擊第二個時第一個才切換。經典的「取消選取」與「選取」事件混淆。
// 錯誤:didDeselect = 取消選取時觸發
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
// 切換圖片邏輯...
}
// 正確:didSelect = 選取時觸發
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
// 切換圖片邏輯...
[collectionView reloadItemsAtIndexPaths:@[indexPath]]; // 局部重載更高效
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSMutableArray *images = self.arrayOfImages; // 假設為可變陣列
NSString *current = images[indexPath.item];
NSString *next;
if ([current isEqualToString:@"dog.png"]) next = @"cat.png";
else if ([current isEqualToString:@"cat.png"]) next = @"lion.png";
else next = @"dog.png";
images[indexPath.item] = next;
[collectionView reloadItemsAtIndexPaths:@[indexPath]];
}
reloadItemsAtIndexPaths: 替代 reloadData,避免整體閃爍且效能更好。cellForItemAtIndexPath 根據模型設定圖片,不要在 Cell 內部保留狀態。collectionView.allowsMultipleSelection = YES。| 方法 | 觸發時機 | 用途 |
|---|---|---|
| didSelectItemAtIndexPath | 使用者點選 Cell | 處理選取動作(導航、切換狀態) |
| didDeselectItemAtIndexPath | 使用者取消選取(多選模式) | 處理取消選取動作 |
| shouldSelectItemAtIndexPath | 點選前詢問 | 決定是否允許選取 |
| shouldDeselectItemAtIndexPath | 取消選取前詢問 | 決定是否允許取消選取 |
一字之差(Select vs Deselect)導致完全相反的行為,閱讀文件與斷點調試是避免此類低級錯誤的關鍵。