尝试创建UicollectionViewCell时断言失败



我正在尝试使用自定义NIB创建UicollectionView。为此,我正在做同样的事情,我正在使用UitaiteView:

myCollectionViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    myCollectionView.delegate = self;
    myCollectionView.dataSource = self;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCollectionCell *cell = [MyCollectionCell newCellOrReuse:collectionView atIndexPath:indexPath];
    return cell;
}

mycollectioncell.m

+ (MyCollectionCell *)newCell
{
    UIViewController *vc = [[UIViewController alloc] initWithNibName:@"MyCollectionCell" bundle:nil];
    MyCollectionCell *cell = (MyCollectionCell *)vc.view;
    [cell initCell];
    return cell;
}
+ (MyCollectionCell *)reuse:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath
{
    NSString *rid = @"MyCollectionCell";
    return (MyCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:rid forIndexPath:indexPath];
}
+ (MyCollectionCell *)newCellOrReuse:(UICollectionView *)collectionView atIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionCell *cell = [MyCollectionCell reuse:collectionView atIndexPath:indexPath];
    if (!cell) cell = [MyCollectionCell newCell];
    return cell;
}
- (void) initCell
{
}

我有一个错误

*** Assertion failure in -[UICollectionView _dequeueReusableViewOfKind:withIdentifier:forIndexPath:], /SourceCache/UIKit/UIKit-2380.17/UICollectionView.m:2249

在这条线上

return (MyCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:rid forIndexPath:indexPath];

我真的没有得到正在发生的事情。它与重复使用有关,因为如果我只调用 [MyCollectionCell newCell];,它就起作用。实际上,它仅在ios6上起作用。在ios7上,我得到*** Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:], /SourceCache/UIKit_Sim/UIKit-2903.23/UICollectionView.m:1367

感谢您的帮助!

- (void)viewDidLoad {
    [super viewDidLoad];
    myCollectionView.delegate = self;
    myCollectionView.dataSource = self;
    [collectionView registerNib:[UINib nibWithNibName:@"MyCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"MyCollectionCell"];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *rid = @"MyCollectionCell";
    return (MyCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:rid forIndexPath:indexPath];
}

然后在mycollectioncell.m中取消所有类方法,然后从Awakefromnib致电initCell。即:

-(void)awakeFromNib {
    [super awakeFromNib];
    [self initCell];
}

相关内容

最新更新