Reputation: 676
please bear with me as I am new to swift programming.
I have a myCollectionViewController
that is a subclass of UICollectionViewController
. The cells for the MyCollectionViewController
are a class of MyCollectionViewCell
, which is a custom UICollectionViewCell
.
What I am trying to do is change the background of the MyCollectionViewCell
based on the user selection AND have this selection persist when the user scrolls to other cells of the MyCollectionViewController
. I have tried two ways to do this, and so far both have failed.
The first way was to write code in the didSelectItemAt
method of the MyCollectionViewController
:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! MyCollectionViewCell
cell.contentView.backgroundColor = UIColor.red
}
However, this did not work and the cell colour was not changed.
The other way I tried to do this was by changing the isSelected
property of the MyCollectionViewCell
.
override var isSelected: Bool {
// Change what happens when the user selects a cell
didSet {
if self.isSelected {
self.contentView.backgroundColor = Colours.primary
} else {
self.contentView.backgroundColor = Colours.secondary
}
}
}
Although this worked, the selection did not persist. That is when the user scrolled to a different cell in the collectionView
and then scrolled back, the selection was gone.
Any advice would be appreciated.
Upvotes: 1
Views: 449
Reputation: 100533
Don't use dequeue in didSelectItemAt
as it'll return other cell than the clicked
var allInde = [IndexPath]()
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at:indexPath) as! MyCollectionViewCell
cell.contentView.backgroundColor = UIColor.red
if !(allIndex.contains(indexPath)) {
allInde.append(indexPath)
}
}
and in cellForItem check whether indexpath to show is in the array and color it
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "id", for: indexPath as IndexPath) as! MyCollectionViewCell
if allIndex.contains(indexPath) {
cell.contentView.backgroundColor = Colours.primary
}
else {
cell.contentView.backgroundColor = Colours.secondary
}
}
// se here updated code
Upvotes: 2