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

Posted

技术标签:

【中文标题】尝试将节页脚添加到 UICollectionView 时崩溃【英文标题】:Crash when trying to add section footer to UICollectionView 【发布时间】:2013-01-19 02:13:03 【问题描述】:

我正在尝试向 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];

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);

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

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

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array”

我不知道这可能是哪个数组,Google 也没有提供任何帮助。有任何想法吗?我一定是忘了连接什么东西,但我找不到。

【问题讨论】:

你有没有想过这个问题?我现在遇到了完全相同的崩溃,但对于标题。您的帖子是唯一的 Google 搜索结果。 对不起,我放弃了,把白线放在 PickerOpenCell.xib 中,这样我就可以跳过页脚了。这可能是一个错误,但我当时没有时间报告它,我现在不得不记住太多细节。如果您报告它,请在此处留下错误编号,我会复制它。 【参考方案1】:

我遇到了这个问题。在

处设置断点
[collectionView setCollectionViewLayout:flowLayout];

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

(lldb) expr collectionView.collectionViewLayout

我猜这不是你所期望的 nil,而是一个 UICollectionViewFlowLayout 指针。很可能您已在界面生成器中将 Collection View 的 Layout 属性设置为“流动”。

不要实例化另一个流布局,只需使用已经存在的布局。

UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*) collectionView.collectionViewLayout;

这解决了我的问题

【讨论】:

对我来说也是如此。谢谢。

以上是关于尝试将节页脚添加到 UICollectionView 时崩溃的主要内容,如果未能解决你的问题,请参考以下文章

在 UITableView 的表格部分下添加文本

将节标题添加到uitableview后删除行的问题

刷新 UITableView tableFooterView 而不重新加载整个表数据

UITableView tableFooterView 显示在 UITableView 的顶部 - 错误

指定表格页脚时,最后一个单元格上缺少 uitableview 分隔符

如何将页脚视图添加到 SwiftUI 中的列表?