【问题标题】:Creating an empty collection view cell throws error创建一个空的集合视图单元格会引发错误
【发布时间】:2014-06-13 13:48:08
【问题描述】:

我正在使用 UICollectionView 和自定义 UICollectionViewCell

我使用以下方法创建了一个空单元格:

[[MyCell alloc] init];

编译器抛出错误:

Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:]

我在viewDidLoad:方法中尝试了以下:

[self.collection registerClass:[MyCell class] forCellWithReuseIdentifier:@"MyCell"];

然后在- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath方法中:

MyCell *cell = [[MyCell alloc] init];

【问题讨论】:

  • 这可能是因为您没有使用任何reuseIdentifier
  • @Morpheus 你有什么建议?

标签: ios objective-c ios7 uicollectionview uicollectionviewcell


【解决方案1】:

如果集合视图尚不存在,则必须告诉集合视图如何创建相应的视图。为此,您必须在集合视图中注册类或 nib 文件。使用这些方法中的任何一种

- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerClass:(Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;

Go through this portion for more details

【讨论】:

  • 我在viewDidLoad: 中添加了[self.collection registerClass:[MyCell class] forCellWithReuseIdentifier:@"cellIdentifier"];,但仍然因同样的错误而崩溃。我在情节提要中创建了这个单元格并为它上课。
【解决方案2】:

在实现文件中创建一个常量NSString 标识符。

static NSString * const CustomClassCellIdentifier = @"Cell";

然后在viewDidLoad:

[self.collectionView registerNib:[UINib nibWithNibName:@"CustomClassCell" bundle:nil] forCellWithReuseIdentifier:CustomClassCellIdentifier];

//[self.collectionView registerClass:[CustomClassCell class] forCellWithReuseIdentifier:CustomClassCellIdentifier];

然后在dataSource方法中

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomClassCell *customCell =
        [collectionView dequeueReusableCellWithReuseIdentifier:CustomClassCellIdentifier
                  forIndexPath:indexPath];

    return customCell;
}

【讨论】:

  • 我需要空单元格。使用dequeueReusableCellWithReuseIdentifier: 会给单元格设置一些值。
  • 你在使用故事板吗?
  • 现在检查已编辑的答案,如果您使用 nib 文件进行 customCell
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多