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

iOS UICollectionView 點擊 Cell 圖片不切換:誤用 didDeselectItemAtIndexPath

     編輯:程式設計綜合問答

問題現象

實作 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,避免整體閃爍且效能更好。
  • 資料模型分離:圖片名稱陣列應為 ViewController 屬性,而非硬編碼在 delegate 中。
  • Cell 複用:在 cellForItemAtIndexPath 根據模型設定圖片,不要在 Cell 內部保留狀態。
  • 允許多選:若需多選,設定 collectionView.allowsMultipleSelection = YES。

常見 Delegate 混淆對照

方法觸發時機用途
didSelectItemAtIndexPath使用者點選 Cell處理選取動作(導航、切換狀態)
didDeselectItemAtIndexPath使用者取消選取(多選模式)處理取消選取動作
shouldSelectItemAtIndexPath點選前詢問決定是否允許選取
shouldDeselectItemAtIndexPath取消選取前詢問決定是否允許取消選取

一字之差(Select vs Deselect)導致完全相反的行為,閱讀文件與斷點調試是避免此類低級錯誤的關鍵。

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