![](/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.