Reputation: 1210
I have a UICollectionView
that contains custom UICollectionViewCell
's, here is the relevant code:
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:
Upvotes: 1
Views: 940
Reputation: 4596
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.
Please make sure to not initialize any views within collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)
for performance reasons. Just assign the appropriate image to the imageView that belongs to the cell.
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()
.
Upvotes: 2