I've created a custom collectionView cell class that contains a UIButton. So each cell contains it's own button that a user can press. However whenever one cell button is tapped it causes background color changes to buttons in other cells. I want it to where only the selected button's background color is changed instead and to prevent the change to other buttons. Below is my code:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! SubjectsCell
cell.subjectButton.setTitle(subjectNames[indexPath.row], for: .normal)
cell.subjectButton.addTarget(self, action: #selector(updateBackgroundColor(_:)), for: .touchUpInside)
if cell.subjectButton.isChosen == selectedState{
cell.subjectButton.backgroundColor = .green }
else if cell.subjectButton.isChosen != selectedState {
cell.subjectButton.backgroundColor = UIColor(red: 34.0/255.0, green: 210.0/255.0, blue: 255.0/255.0, alpha: 1)
}
return cell
I realize that dequeueReusableCell causes some cells to be reused, if this is my problem how I prevent cell changes happening to random cell's and only affect the cell that the tapped button is in.
You're right that dequeueReusableCell(withReuseIdentifier:for:)
is the source of the issue here! You just need to have your cell class override UICollectionReusableView
's prepareForReuse()
method and reset the background to whatever it needs to be.
You may need to change your data model so you have a way of remembering which cells have had the button pressed since the cells can't hold on to that data without causing problems.
Also note that calling addTarget
inside that collectionView(_:cellForItemAt:)
may cause problems later, targets are typically only added once when the object is set up initially. To avoid issues you should set that up either in the nib / storyboard as an action, or when you setup the view objects if you're doing programmatic view setup.