我尝试使用自定义nib创建UICollectionView。为此,我做了与UITableView相同的事情:
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
感谢您的帮助!
答案 0 :(得分:0)
- (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];
}