![](/img/trans.png)
[英]Center First UICollectionViewCell in UICollectionView
[英]Can only change the first cells image in a UICollectionView with custom UICollectionViewCell class
所以我试图用我存储在数组中的图像填充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")
我觉得我某种程度上只能制作自定义类的一个实例。
有任何想法吗?
太感谢了
仍然无法使它正常工作并仍在寻找答案。 我想不出任何原因。 有人经历过吗?
不知道是否有人仍然感兴趣,但是可以肯定,您要做的就是改变
imageView!.frame = frame
至
imageView!.frame = bounds
而且你应该是黄金的。 对我有用
indexPath.row
用于UITableView
indexPath.item
用于UICollectionView
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.