创建一个空的集合视图单元格会引发错误

时间:2014-04-28 06:23:29

标签: ios objective-c ios7 uicollectionview uicollectionviewcell

我正在使用自定义UICollectionView的{​​{1}}。

我使用:

创建一个空单元格
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

2 个答案:

答案 0 :(得分:0)

如果尚不存在,则必须告知集合视图如何创建相应的视图。为此,您必须使用集合视图注册类或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

答案 1 :(得分:0)

在实现文件中创建一个常量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;
}