自定义UICollectionViewCell中的UILabel始终为空,无法更新文本。

16

我创建了一个非常简单的集合视图,类似于苹果的集合视图示例项目。在Storyboard中的View Controller中有一个集合视图,并在集合视图单元格的右上部分设置了一个标签。我已将其连接到自定义单元格中的IBOutlet。以下是相关代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.workoutView registerClass:[Cell class] forCellWithReuseIdentifier:@"Cell"];
    ...
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.collView) {
        Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];    
        cell.segmentTitle.text = @"some text";
        cell.backgroundColor = [UIColor whiteColor];
        return cell;
    }
    return nil;
}

segmentTitle.text之后,我设置了一个断点,但segmentTitle始终为空。因此,在模拟器中看到的是空白的白色框。我错过了什么吗?

2个回答

41

在Storyboard中,UICollectionViewCell不需要注册类(registerClass),只需要在Storyboard中选择重用标识(reuseidentifier)即可。删除这一行代码:

   // [self.workoutView registerClass:[Cell class] forCellWithReuseIdentifier:@"Cell"];

确保正确连接:

-在storyBoard中将UICollectionViewCell的class类型选择为Cell

-将UILabel拖动到Cell中并连接到Cell.h

-输入重用标识符


5
从Storyboard中移除注册行并使用重用标识符解决了问题。谢谢! - brodney
2
这个可行。有时候,故事板中会有太多的魔法。 - Albin Stigo
1
@Signo 在你的故事板中输入它。 - LE SANG
谢谢,它解决了我的错误...我花了1.5个宝贵的小时在它上面。 - Arpit B Parekh
尝试了几个小时才弄清楚为什么这不起作用。删除registerClass后问题迎刃而解。 - grayson
显示剩余2条评论

2
MainFeedCollectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")

我从代码中删除了这一行,现在它可以正常工作了...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接