9

我刚刚开始第一次玩 UICollectionView。似乎工作得很好,但有一个问题和一个关于它的问题。

我的 UICollectionView 设置如下,并带有一个自定义单元格:

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

- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
    return 1;
}

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

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(145, 95);
}

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

所以这都是花花公子,但是我已将此行添加到viewDidLoad

[collectionView registerClass:[ContactCell class] forCellWithReuseIdentifier:@"Cell"];

这造成了麻烦,我不明白为什么。当我启用此行时,我的所有单元格都变为空白。怎么会?我错过了什么?

另外,据我了解,如果该行启用可重用单元格,为什么我必须使用集合视图而不是表视图?

4

2 回答 2

26

您的情节提要会自动注册您在情节提要中设计的单元格,以获取您在界面构建器的右侧窗格中为该单元格指定的重用标识符。通过为该重用标识符重新注册您的类,集合视图只需在您的子类上调用 alloc init 并期望以编程方式设置视图。

文档中

如果您之前使用相同的重用标识符注册了类或 nib 文件,则您在 cellClass 参数中指定的类将替换旧条目。如果你想从指定的重用标识符中注销类,你可以为 cellClass 指定 nil。

如果您想在故事板之外设计单元格,您可以以编程方式设置界面或在单独的 xib 中设置单元格,然后调用

- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier

笔尖必须有一个顶级视图,它是您的自定义子类的一个单元格,并在界面构建器中设置了正确的重用标识符。

于 2012-11-05T00:42:03.397 回答
1

消除

[self.collectionview registerClass:[NewCell class] forCellWithReuseIdentifier:@"Cell"];

对于故事板,我们不需要这条线

于 2017-07-25T13:45:49.570 回答