gpt4 book ai didi

swift - CollectionView.cellForItem 返回 nil

转载 作者:行者123 更新时间:2023-11-30 10:32:13 28 4
gpt4 key购买 nike

我在 Storyboard 中创建了一个 collectionView,然后将 Delegate 和 DataSource 方法放入管理该屏幕的 ViewController 的扩展中。

collectionView 使用layoutDelegate 来显示四乘四的图像网格。所有单元格都显示在网格中,因此单元格不可见不是问题,它们都是类 imageCVC 的实例,该类是 UICollectionViewCell

的子类>

这一切加载都没有问题,但我现在想在将控制权传递给用户之前操​​作四个随机图像。请注意,在 viewDidLoad 结束时,collectionView 可能尚未完全加载,我在 viewDidLayoutSubviews< 中调用选择要操作的图像的例程 changeImages()/ 方法。功能如下:

func changeImages() {
collectionView.layoutIfNeeded()

let maxChanges = 30
var imageIndex = 0
var imageChanges 0

while imageChanges < maxChanges {
imageIndex = Int.random(in: 0..<(collectionView.numberOfItems(inSection: 0)))
if let cell = collectionView.cellForItem(as: IndexPath(row: imageIndex, section: 0)) as? imageCVC {
changeCell(cell)
imagesChanges += 1
}
}
}

(编辑:合并了 Sam 的建议(如下),但它仍然总是返回 nil!)

不幸的是,虽然 imageIndex 设置正确(因此集合知道它有多少个元素),但 cellForItem 调用始终返回 nil。我已经在函数的开头强制布局了,但是没有效果。

请有人让我知道我做错了什么?非常感谢。

最佳答案

在以下行中:

imageIndex = Int.random(in: 0...(collectionView.numberOfItems(inSection: 0)))

代码从 0 开始,一直到 Collection View 项目计数,因此如果计数为 10,则代码从 0 到 10,其中包括 10,总共 11 个项目。这可能是导致崩溃的原因,因为只有 10 个项目,而我们尝试访问 11 个项目。

只需更改:

0...(collectionView.numberOfItems(inSection: 0)

0..<(collectionView.numberOfItems(inSection: 0)

关于swift - CollectionView.cellForItem 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58901216/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com