Reputation: 47
I have a button inside a UICollectionViewCell
(custom class) in a UICollectionView
. When the button is clicked, it changes its background color. Works perfectly at first, but when I change the background color of the main view, I can't update the background color of the button. The background colors are stored in an array and here's the cell set-up function:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("Rebuilding cells")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ColorCollectionViewCell
cell.button.tappedColor = backgroundColors[section]
cell.button.originalColor = backgroundColors[section + 1]
cell.button.delegate = self
cell.button.addTarget(self, action: #selector(didHitButton), for: .touchUpInside)
return cell
}
So if I start with section
as 1, it loads the cell's button with the proper background color (black which is the first color in the section array. Then, I set the count to zero and grid.reloadData()
which successfully wipes out the cells.
But then when I set section
to 2 and reset the total cell count again, the cells don't adopt the new background color (section 2 color is green). They stay black from section 1.
How would I go about telling the UICollectionView
to repaint the button background color in the cell when the data updates, where that background color comes from an array based on a variable for the index
?
Upvotes: 0
Views: 535
Reputation: 324
I think you should be using the .backgroundColor
property of the views to set the background color to display it.
Other than that, with each tableView.reload()
all your tableView delegate methods are called again and your cells are re-binded with the data that you provide... so you have to treat them like they're un-initialized. This could also point out to, that if you're not getting the right colors assigned, black might be their default color and maybe its not working for section
1 as well or you should check the data stored in your array (you can debug or print them).
For a cleaner flow of logic just do:
if indexPath.section == 0 {
// do this for section 0
} else if indexPath.section == 1 {
// do this for section 1
} else {
// for all other if any
}
Hope this helps you in someway...
Upvotes: 0