【问题标题】:Can only change the first cells image in a UICollectionView with custom UICollectionViewCell class只能使用自定义 UICollectionViewCell 类更改 UICollectionView 中的第一个单元格图像
【发布时间】:2019-04-03 09:18:02
【问题描述】:

所以我试图用存储在数组中的图像填充 collectionView。这是我的代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImageCollectionViewCell

    if (indexPath.row % 2 == 0) {
        cell.backgroundColor = UIColor.orangeColor()
    }
    else {
        cell.backgroundColor = UIColor.blackColor()
    }

    let img = poiImages.objectAtIndex(indexPath.row) as? UIImage
    cell.assignImage(img!)

    return cell
}

背景颜色正确更改,我将其作为初始测试来验证该方法是否有效。但是,我只能为第一个单元格分配一个图像。此后的所有单元格都留空,但仍分配有黑色/橙色。

这是我的 UICollectionViewCell 的自定义类代码:

import UIKit

class ImageCollectionViewCell: UICollectionViewCell {
    var imageView: UIImageView!

    override init(frame: CGRect) {
        imageView = UIImageView()
        imageView!.frame = frame
        imageView!.clipsToBounds = true
        imageView!.contentMode = UIViewContentMode.ScaleAspectFill // maybe change to fit
        super.init(frame: frame)

        contentView.addSubview(imageView!)
    }

    func assignImage(img: UIImage) {
        imageView!.image = img
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

在我的视图的初始化程序中,我记得在其中嵌入了集合视图:

poiImageView.registerClass(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

我觉得我只是在制作我的自定义类的一个实例。

有什么想法吗?

谢谢一百万

编辑

仍然无法使其正常工作并仍在寻找答案。我想不出发生这种情况的任何原因。有没有人有同样的经历?

【问题讨论】:

  • 你检查poiImages数组是否有图像并且不返回nil
  • 是的,我检查过了,一切看起来都很好。还要确保这不是问题的根源,我将其卡在静态图像中,以便我知道它在那里。再次只更新了第一个单元格。我很困惑哈哈
  • 这可能不是问题的根源,但您应该将 super.init(frame: frame) 放在覆盖的 init(frame:_) 方法的开头。如果您的单元格的imageViewimage 属性中有任何内容,您是否还检查了视图调试器或通过LLDB?
  • 嗨。我只将代码放在 init(frame:_) 之前作为解决问题的最终尝试。我已经把它放回去了,问题仍然存在。我还检查了 LLDB,并且 imageview 确实有一个图像集。
  • 我也面临同样的问题。只有第一个单元格得到更新。有什么解决办法吗?

标签: ios swift uicollectionview uicollectionviewcell


【解决方案1】:

不确定是否有人仍然感兴趣,但很确定你需要做的就是改变

imageView!.frame = frame

imageView!.frame = bounds

你应该是金色的。它对我有用

【讨论】:

    【解决方案2】:

    indexPath.row 用于UITableView

    indexPath.item 代表UICollectionView

    【讨论】:

    • 我认为使用 .row 似乎很奇怪。我已经切换了它,但不幸的是,这并不能解决我更大的问题。不过,为输入干杯。
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多