美文网首页
iOS开发 - 解决UICollectionViewCell/U

iOS开发 - 解决UICollectionViewCell/U

作者: 俺不是大佬儿 | 来源:发表于2020-04-06 17:26 被阅读0次

这篇是我多年前写在博客园上的一篇关于UICollectionViewCell/UITableViewCell因重用机制导致cell选中项错乱的解决方法,记忆很深刻,近日有朋友问起将文章转移一下。

情景一:

在显示以及选择商品的属性时(商品的属性属于分类属性)每滑动一次页面显示属性的cell位置就会错乱,选择时就会出现选择的index对数组溢出;

情景二:

在某个功能情境下需要展示商城商品品牌并且进行多选,选中的和未选中的要有状态区分,但每次选择后滑动液面就会出现已选择的和页面上的状态不对应出现了错乱的状态。

实际上这些问题是由于设置选中状态的方式和位置不恰当造成的,应该给数据Model添加是否是选中项的字段,下面这种只是补救的方法:

先定义一个可变的的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时同样可以用这样的方法来解决再次不再具体说明:

博客园原文:https://www.cnblogs.com/Rong-Shengcom/p/6491805.html

相关文章

网友评论

      本文标题:iOS开发 - 解决UICollectionViewCell/U

      本文链接:https://www.haomeiwen.com/subject/vybbphtx.html