首页 > 解决方案 > 将新初始化的 UIImageView 传递给类的属性(类型 UIImageView)给出零?

问题描述

我有一个CustomCollectionViewController和一个CustomCollectionViewCell。我将 a 拖放UIImageViewCustomCollectionViewCell故事板上并将其绑定在代码中。

然后我尝试collectionView(_:cellForItemAt:)用这一行初始化单元格:

customCell.imageView = UIImageView(image: images[indexPath.item])

它不起作用,customCell.imageViewnilcollectionView(_:cellForItemAt:)返回时。但是imageCell.imageView.image = images[indexPath.item],它起作用了。

为什么呢?谢谢。


代码片段:

里面class CustomCollectionViewController

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath)

    if let imageCell = cell as? ImageCollectionViewCell, images[indexPath.item] != nil {
        imageCell.imageView = UIImageView(image: images[indexPath.item])  // doesn't work, cell.imageView would be nil
        imageCell.imageView.image = images[indexPath.item]  // work
    }

    return cell
}

和:

class CustomCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!
}

标签: iosswift

解决方案


长答案:

让我们将您的旧 ImageView(故事板中的那个)命名为 A,将新的 ImageView(在代码中创建)命名为 BUIImageView(image: images[indexPath.item]) 该变量将被称为只是引用

您已将引用设置为弱引用,这意味着,一旦它失去任何强引用(例如在视图层次结构中),它就会被销毁。当您将其分配给 B 时,该 B 没有分配给其他任何地方,因此它立即被销毁,因此您的引用变为 nil。只要您将 A 从层次结构中删除,您的 A 仍然在单元格上(在子视图中数组和数组往往包含强引用)。您必须了解链接引用(弱或强)与视图中的子视图(强)之间的区别。在您对代码进行任何更改之前,A imageView 有两个链接——代码中的弱指针和单元格层次结构中的强指针。当您将引用替换为 B 时,A 失去了弱引用,但单元格本身仍然具有强引用。B只有弱,所以它在任何实际使用之前立即被销毁

你的逻辑也有问题。仅仅因为您更改了对 B imageView 的引用,并不意味着该图像将出现在您的单元格中。您的 B 需要设置它的框架或约束并添加到某些视图层次结构(单元格)中。您真正需要的只是将您的 A.image 属性更改为您的新图像,仅此而已imageCell.imageView.image = images[indexPath.item]

请阅读有关内存管理和弱强引用的更多信息

简短的回答:

删除此行

imageCell.imageView = UIImageView(image: images[indexPath.item])

所以你的代码看起来像

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath)

    if let imageCell = cell as? ImageCollectionViewCell,
       let image = images[indexPath.item]
    {
        imageCell.imageView.image = image
    }

    return cell
}

推荐阅读