首页 > 解决方案 > 无法在 CollectionViewCell 中设置 imageView

问题描述

在我的代码中,我试图设置 UICollectionViewCell 的 imageView。imageView 在 CollectionViewCell 类中称为 cellImageView。当应用程序加载时,它会尝试初始化此值,但它不起作用

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selectCell", for: indexPath) as! PhraseSelectionCell
    cell.cellImageView?.image = UIImage(named: "lol")
    return cell
}

UICollectionViewCell 的类

class PhraseSelectionCell: UICollectionViewCell {
@IBOutlet var cellImageView: UIImageView!

}

标签: iosswiftdebugginguicollectionviewcell

解决方案


尝试这种方式调试,然后您可以找到错误所在。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "selectCell", for: indexPath) as! PhraseSelectionCell

//debug 1
if UIImage(named: "lol") == nil {
    print("image is nil, double check image name")
}

//debug 2
if cell.cellImageView == nil {
    print("cellImageView outlet is nil")
}

cell.cellImageView?.image = UIImage(named: "lol")
return cell

}


推荐阅读