我有一个问题我现在几个小时都无法解决...
我有多个 UICollectionViews 具有不同数量的单元格和不同的单元格大小。CollectionViews 以编程方式创建,并且设置了委托和数据源。
集合视图是这样创建的:
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
[layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
collectionViewOne = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,320,150) collectionViewLayout:layout];
[collectionViewOne setTag:99];
[collectionViewOne setDataSource:self];
[collectionViewOne setDelegate:self];
[collectionViewOne registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
[collectionViewOne setBackgroundColor:bgColor];
[collectionViewOne setShowsHorizontalScrollIndicator:NO];
[collectionViewOne setBounces:YES];
[collectionViewOne setAlwaysBounceHorizontal:YES];
[collectionViewOne setScrollEnabled:YES];
[collectionViewOne setRestorationIdentifier:@"collectionViewOne"];
[scrollView addSubview:collectionViewOne];
我的功能是这样的:
- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section {
NSLog(@"restorationIdentifier: %@", collectionView.restorationIdentifier);
if (collectionView == collectionViewOne)
{
return 3;
}
else if (collectionView == collectionViewTwo)
{
return 4;
}
else
{
return 1;
}
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"restorationIdentifier: %@", collectionView.restorationIdentifier);
if (collectionView == collectionViewOne)
{
return CGSizeMake(100, 150);
}
else if (collectionView == collectionViewTwo)
{
return CGSizeMake(200, 150);
}
else
{
return CGSizeMake(200, 150);
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"restorationIdentifier: %@", collectionView.restorationIdentifier);
if (collectionView == collectionViewOne)
{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.image = [UIImage imageNamed:@"image.png"];
[cell addSubview:imageView];
}
else if (collectionView == collectionViewTwo)
{
//create cell of type 2
}
return cell;
}
在我的日志中,我得到以下输出(例如):
numberOfItemsInSection 中的恢复标识符:(空) sizeForItemAtIndexPath 中的恢复标识符:(空)恢复标识符 cellForItemAtIndexPath:collectionViewOne
collectionViewOne 是 collectionViewOne 上的恢复标识符。那么为什么前两种方法都不能识别呢?
当然,结果是我崩溃了,因为不同 CollectionViews 中的单元格大小和单元格数量没有正确设置。错误:
*** Assertion failure in -[UICollectionViewData validateLayoutInRect:], /SourceCache/UIKit_Sim/UIKit-2903.2/UICollectionViewData.m:341
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView recieved layout attributes for a cell with an index path that does not exist: <NSIndexPath: 0x8c31c10> {length = 2, path = 0 - 2}'
我怎样才能解决这个问题?