iOS Assertion Failure in UICollectionView

后端 未结 7 1361
抹茶落季
抹茶落季 2020-12-17 08:07

I\'m getting the error ...

*** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:], /SourceCache/UIKit/UIKit-237         


        
相关标签:
7条回答
  • 2020-12-17 09:05

    I have seen this error pop up when using multiple UICollectionViews with unique ReuseIdentifiers. In ViewDidLoad you want to register each CollectionView's reuseIdentifier like so:

    [_collectionView1 registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionView1CellIdentifier"];
    [_collectionView2 registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionView2CellIdentifier"];
    

    Then when you get to "- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath" you want to make sure that you don't try to set a cell for collectionView1 to the reuseIdentifier for collectionView2 or you will get this error.

    DON'T DO THIS: (Or collectionView2 will see the wrong Identifier and throw a fit before seeing the identifier it was expecting)

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView1CellIdentifier" forIndexPath:indexPath];
    
    if(collectionView != _collectionView1){
       cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView2CellIdentifier" forIndexPath:indexPath];
    }
    
    cell.backgroundColor = [UIColor greenColor];
    return cell;
    

    DO THIS:

    UICollectionViewCell *cell;
    
    if(collectionView == _collectionView1){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView1CellIdentifier" forIndexPath:indexPath];
    }else{
       cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionView2CellIdentifier" forIndexPath:indexPath];
    }
    
    cell.backgroundColor = [UIColor greenColor];
    return cell;
    
    0 讨论(0)
提交回复
热议问题