解決UICollectionViewCell/UITableViewCell因重用機制導致的錯亂問題
UICollectionView和UITableView在開中用的很多,可以解決很多復雜的布局問題,在設計列表式的頁面布局時用到的更多,但有時因為設置不當會出現cell的內容錯亂的問題。
就拿我遇到的問題舉例:
情景一:
在顯示以及選擇商品的屬性時(商品的屬性屬於分類屬性)每滑動一次頁面顯示屬性的cell位置就會錯亂,選擇時就會出現選擇的index對數組溢出;
情景二:
在某個功能情境下需要展示商城商品品牌並且進行多選,選中的和未選中的要有狀態區分,但每次選擇后滑動液面就會出現已選擇的和頁面上的狀態不對應出現了錯亂的狀態。
具體的解決方法:
1.先定義一個可變的的dictionary(NSMutableDictionary)
- (UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSString *identifier = [_cellIdentifierDic objectForKey:[NSString stringWithFormat:@"%@", indexPath]]; if(identifier == nil){ identifier = [NSString stringWithFormat:@"selectedBtn%@", [NSString stringWithFormat:@"%@", indexPath]]; [_cellIdentifierDic setObject:identifier forKey:[NSString stringWithFormat:@"%@",indexPath]]; // 注冊Cell(把對cell的注冊寫在此處) [_collectionView registerClass:[SelectedBtnCell class] forCellWithReuseIdentifier:identifier]; } SelectedBtnCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; if(!cell){ cell = [[[NSBundle mainBundle]loadNibNamed:@"SelectedBtnCell" owner:self options:nil]lastObject]; } //商品規格信息邏輯 }
注:在使用UITableViewCell時同樣可以用這樣的方法來解決再次不再具體說明:
這樣就可以解決上面出現的問題,其實原理也很容易理解如果有更先進的解決方法歡迎來訪(http://www.cnblogs.com/Rong-Shengcom/);