UICollectionView registerCell - 空白单元格

2023-12-19

我刚刚开始第一次使用 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"];

这引起了麻烦,我不明白为什么。当我启用此行时,我的所有单元格都会变为空白。怎么会?我缺少什么?

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


您的故事板会自动注册您在故事板中设计的单元格,以用于您在界面生成器的右侧窗格中为该单元格指定的重用标识符。通过为该重用标识符重新注册您的类,集合视图只需在您的子类上调用 alloc init 并期望以编程方式设置视图。

From 文档 http://developer.apple.com/library/ios/#documentation/uikit/reference/UICollectionView_class/Reference/Reference.html:

如果您之前注册了具有相同重用的类或 nib 文件 标识符,您在 cellClass 参数中指定的类替换 旧条目。如果你愿意,你可以为 cellClass 指定 nil 从指定的重用标识符中取消注册该类。

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UICollectionView registerCell - 空白单元格 的相关文章

随机推荐