所以我找到了这个非常奇怪的错误的原因。我的目标是使用包含灵活 UITextField 的单元格创建 UICollectionView。用户在书写时 - 单元格会根据文本字段中的文本高度更改其大小。
为了实现它,我为我的 UICollectionView 使用了这些配置:
Image with UICollectionView configurations
这里可以看到“Cell Size”宽度为0,“Estimate Size”是自动的。它配置为灵活的单元格高度。
为了使其正常工作,我还添加了以下代码:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout,
flowLayout.estimatedItemSize.width == .greatestFiniteMagnitude else {
return
}
flowLayout.estimatedItemSize = CGSize(
width: view.frame.width - Size.verticalCollectionInsetsDistance * 2,
// Make the height a reasonable estimate to
// ensure the scroll bar remains smooth
height: 200
)
}
这里有个技巧:
当我将我的应用程序升级到 iOS 14 最低部署时,此代码已损坏。因为,由于某种原因,当您将“单元大小”宽度设置为 0 并且您有 iOS 13 最小部署时,那么估计的ItemSize.width == .greatestFiniteMagnitude 为真。但是对于 iOS 14 来说,estimatedItemSize.width == .greatestFiniteMagnitude 是假的,而estimatedItemSize.width == 0 是真的。所以现在我通过添加这个条件“flowLayout.estimatedItemSize.width == 0”来修复我的代码。这是最终版本:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout,
flowLayout.estimatedItemSize.width == .greatestFiniteMagnitude || flowLayout.estimatedItemSize.width == 0 else {
return
}
flowLayout.estimatedItemSize = CGSize(
width: view.frame.width - Size.verticalCollectionInsetsDistance * 2,
// Make the height a reasonable estimate to
// ensure the scroll bar remains smooth
height: 200
)
}
附:我仍然不明白为什么 iOS 14estimatedItemSize.width 与 iOS 13 不同。如果您知道答案,请在 cmets 中描述。提前致谢!