UICollectionView设置首个cell默认选中

设置UICollectionView中某个cell的默认选中,刚开始为追求性能,采用同一个cellId去标识UICollectionViewCell,却由于cell的重用会导致之前选中的cell在被重用后并不会响应取消选中的代理方法,会造成多个cell选中的结果。  在- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath代理方法中根据每个indexPath.row去设置每个cell的id,防止cell重用,并保存在一个字典中,并把cell的注册方法放在该代理方法中代码如下:

        NSString *identifier = [self.cellIdentifierDictM objectForKey:[NSString stringWithFormat:@"%@", indexPath]];
        
        if(identifier == nil){
            
            identifier = [NSString stringWithFormat:@"selectedCell%@", [NSString stringWithFormat:@"%zd", indexPath.row]];
            
            [self.cellIdentifierDictM setObject:identifier forKey:[NSString  stringWithFormat:@"%@",indexPath]];
            
            // 注册Cell(把对cell的注册写在此处)
            
            [collectionView registerClass:[LBCollectionFirstCell class] forCellWithReuseIdentifier:identifier];
            
        }

  由于我这边的数据是从网络上加载的,是再加载过数据并刷新之后,设置默认UICollectionView的第一个Cell选中代码如下:

   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
   [self collectionView:self.firstHeadView.catogeryCollectionView didSelectItemAtIndexPath:indexPath];
   [self.firstHeadView.catogeryCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];

 

 

这种方法对于较多cell的话,性能有限,最后提醒不要忘了字典的初始化

转载于:https://www.cnblogs.com/muzichenyu/p/10732959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值