尝试将节页脚添加到UICollectionView时崩溃

jan*_*nne 1 ios uicollectionview uicollectionviewlayout

我正在尝试将一个页脚添加到UICollectionView并以我不理解的方式失败.

我正在设置这样的主单元格:

[collectionView registerClass:[PickerOpenCell class] forCellWithReuseIdentifier:cellIdentifier];
UINib *cellNib = [UINib nibWithNibName:@"PickerOpenCell" bundle:nil];
[collectionView registerNib:cellNib forCellWithReuseIdentifier:cellIdentifier];

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
flowLayout.itemSize = CGSizeMake(130, 50);

[collectionView setCollectionViewLayout:flowLayout];
Run Code Online (Sandbox Code Playgroud)

xib是UICollectionViewCell的子类,只包含一个UILabel.一切正常.

现在我想添加节页脚,所以我添加它(与上面的代码交错,所以setCollectionViewLayout调用仍然是序列中的最后一个):

[collectionView registerClass:[PickerOpenFooter class] forCellWithReuseIdentifier:footerIdentifier];

UINib *footerNib = [UINib nibWithNibName:@"PickerOpenFooter" bundle:nil];
[collectionView registerNib:footerNib forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier];

flowLayout.footerReferenceSize = CGSizeMake(130, 2);
Run Code Online (Sandbox Code Playgroud)

这次的xib是UICollectionReusableView的子类,并包含一个视图(它的意思是各部分之间的水平白线).视图的大小为130 x 2.

我添加footerReferenceSize行的那一刻,应用程序在setCollectionViewLayoutLine上崩溃了

由于未捕获的异常'NSRangeException'终止应用程序,原因:' - [__ NSArrayM objectAtIndex:]:索引0超出空数组的边界'

我不知道这可能是哪个数组,谷歌没有提供任何帮助.有任何想法吗?我一定忘了把事情搞砸了,但我找不到.

小智 5

我遇到了这个问题.设置断点为

[collectionView setCollectionViewLayout:flowLayout];
Run Code Online (Sandbox Code Playgroud)

并使用lldb调试器控制台检查collectionView是否已作为collectionViewLayout实例属性

(lldb) expr collectionView.collectionViewLayout
Run Code Online (Sandbox Code Playgroud)

我猜这不是你所期望的,但实际上是一个UICollectionViewFlowLayout指针.您很可能已将"集合视图"的"布局"属性设置为"界面"构建器中的"流".

而不是实例化另一个流布局,只需使用已存在的那个.

UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*) collectionView.collectionViewLayout;
Run Code Online (Sandbox Code Playgroud)

这为我解决了这个问题