1

我有一个包含 10 个条目的数组。我想在 UICollectionView 上将它们显示为每行 3 个,这样它们就会像

A B C
D E F
G H I
J

现在我正在使用以下代码

#pragma mark - UICollectionView Datasource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    return 3;
}

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
    return [self.btnArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    Buttons *btn = [self.btnArray objectAtIndex:(indexPath.section * indexPath.row)];
    NSURL* aURL = [NSURL URLWithString:btn.imagePath];
    NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];

    cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageWithData:data]];
    return cell;
}

#pragma mark – UICollectionViewDelegateFlowLayout

// 1
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize retval =  CGSizeMake(75, 75);
    return retval;
}

// 3
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(50, 20, 50, 20);
}

但是当我打

 UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

它给了我错误

NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

怎么了?

4

1 回答 1

3

正如错误所说,您需要为具有该标识符的单元格注册一个 nib 或类。设置视图时执行一次。

请参阅 UICollectionView 文档了解这两种方法:

– registerClass:forCellWithReuseIdentifier:
– registerNib:forCellWithReuseIdentifier:
于 2013-03-08T15:50:10.267 回答