UICollectionView - 尝试在 prepareLayout 调用已在进行时准备布局 - Swift
UICollectionView - attempt to prepare a layout while a prepareLayout call was already in progress - Swift
我们有一个水平滚动的 collectionView,它有 2 个部分。
第一个部分包含由数组数据设置的单元格,最后一个部分只有一个单元格,上面写着“添加新项目”(重定向到另一个 viewcontroller)
为了对齐所有这些单元格,我设置了以下代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// "Add new item" cell
if indexPath.section == 2 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAdd", for: indexPath) as! AddCollectionViewCell
let size = cell.itemText.systemLayoutSizeFitting(UIView.layoutFittingExpandedSize)
return CGSize(width: size.width, height: 62)
}
if let items = accountItems {
let cell = ItemCollectionViewCell()
let item = items[indexPath.section].names[indexPath.row]
cell.itemText.text = item.title
let size = cell.itemText.systemLayoutSizeFitting(UIView.layoutFittingExpandedSize)
return CGSize(width: size.width+30, height: 62)
}
return CGSize(width: 100, height: 62)
}
但是当代码在 iOS < 11 的设备中输入 if 语句 (if indexPath.section == 2) 时,应用程序会崩溃。
对于 iOS >= 11 的设备,会抛出警告:
[CollectionView] An attempt to prepare a layout while a prepareLayout call was already in progress (i.e. reentrant call) has been ignored. Please file a bug.
在 iOS < 11 的设备上修复此警告和崩溃的方法有哪些?
对于任何想知道的人,您不应该在 sizeForItemAt 方法中创建单元格。相反,为了计算单元格的宽度或高度,我曾经计算用于填充单元格的字符串大小,如 here
所述
我们有一个水平滚动的 collectionView,它有 2 个部分。
第一个部分包含由数组数据设置的单元格,最后一个部分只有一个单元格,上面写着“添加新项目”(重定向到另一个 viewcontroller)
为了对齐所有这些单元格,我设置了以下代码:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// "Add new item" cell
if indexPath.section == 2 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellAdd", for: indexPath) as! AddCollectionViewCell
let size = cell.itemText.systemLayoutSizeFitting(UIView.layoutFittingExpandedSize)
return CGSize(width: size.width, height: 62)
}
if let items = accountItems {
let cell = ItemCollectionViewCell()
let item = items[indexPath.section].names[indexPath.row]
cell.itemText.text = item.title
let size = cell.itemText.systemLayoutSizeFitting(UIView.layoutFittingExpandedSize)
return CGSize(width: size.width+30, height: 62)
}
return CGSize(width: 100, height: 62)
}
但是当代码在 iOS < 11 的设备中输入 if 语句 (if indexPath.section == 2) 时,应用程序会崩溃。
对于 iOS >= 11 的设备,会抛出警告:
[CollectionView] An attempt to prepare a layout while a prepareLayout call was already in progress (i.e. reentrant call) has been ignored. Please file a bug.
在 iOS < 11 的设备上修复此警告和崩溃的方法有哪些?
对于任何想知道的人,您不应该在 sizeForItemAt 方法中创建单元格。相反,为了计算单元格的宽度或高度,我曾经计算用于填充单元格的字符串大小,如 here
所述