如何注册自定义UICollectionViewCell?

时间:2015-03-28 18:20:19

标签: ios uicollectionviewcell

到目前为止,我已成功使用UITableViews,但我无法让UICollectionView正常工作。

@interface NewsCollectionViewDataSource : NSObject <UICollectionViewDataSource, UICollectionViewDelegate>

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TNCollectionViewCell *newscell = nil;
    newscell = [collectionView dequeueReusableCellWithReuseIdentifier:newsCellReuseIdentifier forIndexPath:indexPath];
    if (!newscell) {
        [[NSBundle bundleForClass:[self class]] loadNibNamed:@"TNCollectionViewCell" owner:self options:nil];
    }
    newscell.newsLabel.text = [[self newsForIndexPath:indexPath] headLine];
    return newscell;
}

每次我每次都到达这条线:

newscell.newsLabel.text = [[self newsForIndexPath:indexPath] headLine];

newscell是零。

我注册错了吗?

1 个答案:

答案 0 :(得分:2)

在检索collectionView的单元格(即viewDidLoad)之前的某处,请调用UICollectionView

的以下方法
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;

在你的情况下,它会是这样的:

[self.collectionView registerNib:[UINib nibWithNibName:@"TNCollectionViewCell" bundle:nil] 
      forCellWithReuseIdentifier:newsCellReuseIdentifier];

然后就不需要以下代码:

if (!newscell) {
    [[NSBundle bundleForClass:[self class]] loadNibNamed:@"TNCollectionViewCell" owner:self options:nil];
}
相关问题