Swift - 无法动态更改UICollectionViewFlowLayout

5

viewDidLoad中,我为UICollectionViewCell设置了一个collectionViewLayout,其中包含一个UILabel,内容为“正在加载内容...”。当应用程序从服务器获取内容时,它执行以下操作:

let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
...
// some configuration for the layout

// here it crash:
collectionView.setCollectionViewLayout(layout, animated: true)

它崩溃并显示以下消息:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' *** First throw call stack: (0x24479b0b 0x23c36dff 0x2438a6d3 0x29275999 0x29271d13 0x29272aaf 0x28be537f 0x28be4667 0x1778dc 0x165f48 0x1661b8 0x16e774 0x16f038 0xf950c 0xf9174 0xdefb0 0xe1934 0xdf98c 0x52ed78 0x52d700 0x52bfc8 0x4df9c0 0x1531ba7 0x1531b93 0x1536659 0x2443b755 0x24439c4f 0x243881c9 0x24387fbd 0x259a4af9 0x28ac0435 0x131254 0x24034873) libc++abi.dylib: terminating with uncaught exception of type NSException

我所做的是设置一个 collectionViewLayout 并将其替换为另一个。

在替换 collectionViewLayout 之前,我尝试使用 invalidateLayout() 来使布局失效,并重新加载或不重新加载 collectionView,但它仍然崩溃。

我该如何动态更改 collectionViewLayout?或者我做错了什么吗?

谢谢


尝试添加异常断点,它可能有助于确定您的问题 - https://developer.apple.com/library/ios/recipes/xcode_help-breakpoint_navigator/articles/adding_an_exception_breakpoint.html - Losiowaty
关于这个问题本身 - 检查你的代码中访问数组的地方,并确保它们实际上有内容。异常信息已经说明了一切。 - Losiowaty
@Losiowaty 我认为数组不是问题,因为如果我不尝试替换 collectionViewLayout,它就完美地工作。 - pableiros
@Losiowaty 我添加了一个异常断点,它会在 collectionView.setCollectionViewLayout(layout, animated: true) 处停止。 - pableiros
好的,你能发更多的代码吗?特别是涉及处理网络响应的部分,包括你已经发布的行和cellForItem...方法的整个方法。如果不太大的话,甚至可以发整个控制器类 ;) - Losiowaty
1
@Losiowaty 我找到了一个实现 UICollectionViewDelegateFlowLayout 的解决方案,我想我会使用那个委托代替整个布局对象。 - pableiros
1个回答

6

我在 iOS9 和 iOS8 上遇到了同样的问题。

在我的情况下,需要在 collectionView.collectionViewLayout.invalidateLayout() 后调用 collectionView.layoutIfNeeded() 来解决问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接