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的話,性能有限,最后提醒不要忘了字典的初始化


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM