UICollectionView registerCell - 空白单元格

Jos*_*ane 9 iphone objective-c ipad uicollectionview

我刚刚第一次开始玩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);
}
Run Code Online (Sandbox Code Playgroud)

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

[collectionView registerClass:[ContactCell class] forCellWithReuseIdentifier:@"Cell"];
Run Code Online (Sandbox Code Playgroud)

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

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

jac*_*ash 25

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

文档:

如果先前使用相同的重用标识符注册了类或nib文件,则在cellClass参数中指定的类将替换旧条目.如果要从指定的重用标识符中取消注册该类,则可以为cellClass指定nil.

如果要设计故事板外部的单元格,可以通过编程方式设置界面,也可以在单独的xib中设置单元格然后调用

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

其中nib必须具有一个顶级视图,该视图是自定义子类的单元格,并在接口构建器中设置了正确的重用标识符.