Reputation: 21
I am using a custom collectionview cell which has a variable called views. For some reason i get the views in the wrong cell and it also sometimes duplicates itself.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: docCellId, for: indexPath) as! DocumentCell
cell.backgroundColor = .white
cell.indexPath = indexPath
cell.views = dic[indexPath] ?? [(UIView(),CGRect.zero)]
cell.label.text = "\(indexPath.row)"
return cell
}
This is in my custom collectionview cell
var views : [(UIView, CGRect)] = [] {
didSet {
addViews()
}
}
fileprivate func addViews() {
for i in views {
addSubview(i.0)
i.0.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: i.1.origin.y, paddingLeft: i.1.origin.x, paddingBottom: 0, paddingRight: 0)
}
}
Upvotes: 0
Views: 175
Reputation: 1081
if you reuse your cell you should override prepareForReuse()
and remove the previously added views otherwise you just will add the views on top of the existing views.
override func prepareForReuse() {
views.forEach { $0.0.removeFromSuperview() }
views = []
}
Regards
Upvotes: 2