问题描述
我特意在我的资产目录中留下了一个空图像,以便我可以让我的 collectionView 在它为零时以某种方式跳过该图像,但到目前为止它会在该单元格中呈现一个空图像。这比让我的应用崩溃要好,但我怎样才能让它跳过那个图像?
这是我的 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
}
解决方法
如果图像为零,您需要修改数据模型以不包含它,并且可以在将其添加到模型之前通过简单的 if 检查来完成,然后您的单元格不会呈现它,因为它从数据中被省略了模型。