【发布时间】:2021-03-11 03:48:18
【问题描述】:
我故意在我的资产目录中留下了一个空图像,以便我可以让我的 collectionView 在它为 nil 时以某种方式跳过该图像,但到目前为止它会在该单元格中呈现一个空图像。这比让我的应用程序崩溃要好,但我怎样才能让它跳过该图像?
这是我的 cellForItemAt indexPath 代码。任何想法将不胜感激。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.collectionViewCell, for: indexPath) as! CollectionViewCell
DispatchQueue.main.async {
let image = RoomModel.roomModel.rooms[indexPath.item]
if let image = image {
cell.imageView.image = image
}
}
return cell
}
模型解决方案:
import UIKit
var data = [long list of UIImage(named: ...)]
class RoomModel {
var rooms = data.compactMap { ($0) }
var roomNo = 0
func setRoomNo(sender: Int) {
roomNo = sender
}
func getRoom() -> UIImage {
let image = rooms[roomNo]
return image
}
}
itemForRow 解决方案:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.collectionViewCell, for: indexPath) as! CollectionViewCell
DispatchQueue.main.async {
cell.imageView.image = self.roomModel.rooms[indexPath.item]
}
return cell
}
【问题讨论】:
-
“跳过该图像”是什么意思?如果你的目标是说
cell.imageView.image = nil为什么不说呢?如果不是,这里的真正目标是什么? -
我试图不渲染一个空单元格,当 indexPath 处的单元格到达空图像对象时,它会显示一个空单元格。我希望它能够识别该 indexPath 处的图像包含 nil,而是将数组中的下一个图像放在单元格中。
-
那你需要改变数据模型。当您被要求提供一个单元格时,忽略它为时已晚。你不会省略一个单元格;你省略了数据。更少的数据,更少的单元格。你有看到?
itemForRow的工作不是思考,而是阵列的工作。 -
哦,谢谢!这很有意义,并解释了为什么我所有的尝试都失败了。我将编写一个函数来获取模型中的数据,并在
itemForRow中调用该函数 -
不仅仅是
itemForRow。所有方法都需要一致地查看数据。这就是为什么你需要数据本身来改变。