【发布时间】: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:_)方法的开头。如果您的单元格的imageView的image属性中有任何内容,您是否还检查了视图调试器或通过LLDB? -
嗨。我只将代码放在 init(frame:_) 之前作为解决问题的最终尝试。我已经把它放回去了,问题仍然存在。我还检查了 LLDB,并且 imageview 确实有一个图像集。
-
我也面临同样的问题。只有第一个单元格得到更新。有什么解决办法吗?
标签: ios swift uicollectionview uicollectionviewcell