我正在使用自定义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
答案 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;
答案 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;
}