[英]UICollectionView custom cells are not displaying
I have a UICollectionView
that contains custom UICollectionViewCell
's, here is the relevant code: 我有一个
UICollectionView
包含自定义UICollectionViewCell
,这是相关的代码:
class customCell: UICollectionViewCell{
var imgView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit(){
imgView.translatesAutoresizingMaskIntoConstraints = false
self.addcontentView.addSubview(imgView)
//add constraints
}
}
class CollectionViewController: UICollectionViewController {
private let imageLib = [...] //image file name strings
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : IconCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(keyIconCellReuse , forIndexPath: indexPath) as! IconCollectionViewCell
let image1 = (UIImage(named: imageLib[indexPath.row])?.imageWithRenderingMode(.AlwaysTemplate))!
cell.imgView = UIImageView(image: image1)
cell.imgView.tintColor = UIColor(white:0, alpha:0.7)
cell.userInteractionEnabled = true
return cell
}
}
This is what it looks like now: 这是现在的样子:
It looks like cell.setup(imageLib[indexPath.row])
adds a new UIImageView
with the new image instead of reusing a existing one in the snipped code parts. 看起来
cell.setup(imageLib[indexPath.row])
用新图像添加了一个新的UIImageView
,而不是在片段代码中重复使用现有的UIImageView
。
Please make sure to not initialize any views within collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)
for performance reasons. 出于性能原因
collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)
请确保不要初始化collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)
任何视图。 Just assign the appropriate image to the imageView that belongs to the cell. 只需将适当的图像分配给属于该单元格的imageView即可。
Note that cells get reused a lot by a collection view. 请注意,收集视图会大量重复使用单元格。
Edit : 编辑 :
With the updated question, you are doing 有了更新的问题,您正在做
let image1 = (UIImage(named: imageLib[indexPath.row])?.imageWithRenderingMode(.AlwaysTemplate))!
cell.imgView = UIImageView(image: image1)
cell.imgView.tintColor = UIColor(white:0, alpha:0.7)
cell.userInteractionEnabled = true
Just 只是
let image1 = (UIImage(named: imageLib[indexPath.row])?.imageWithRenderingMode(.AlwaysTemplate))!
cell.imgView.image = image1
and do as much other setup as possible in commonInit()
. 并在
commonInit()
进行尽可能多的其他设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.