WoShiNiBaBa WoShiNiBaBa - 2 months ago 10
iOS Question

Multiple UICollectionViewCell color gets changed together issue

I have created a

UICollectionView
with 12 cells in it. I would like to have their color changed (to the same color) on tap.

Here is my code :

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)as! InterestCollectionViewCell
print("2 \(cell.interest) \(indexPath.row)")

if cell.selected == true {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.clearColor()
}
}


Issues


  1. Color doesn't change back when tapped again

  2. When I tap on the [0] cell, the [5] and [10] cells changes color as well. Same after I tap on the [1] cell, [6]and [11] cells get called too...etc.m


Answer

Instead of setting color in didSelectItemAtIndexPath set the color in cellForItemAtIndexPath for that you need to declare instance of Int and store the row of collectionView inside that instance like this.

var selectedRow: Int = -1

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
    // Set others detail of cell
    if self.selectedRow == indexPath.item {
        cell.backgroundColor = UIColor.redColor()
    }
    else {
        cell.backgroundColor = UIColor.clearColor()
    }
    return cell
}

Now in didSelectItemAtIndexPath set the selectedRow reload the collectionView.

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    if self.selectedRow == indexPath.item {
        self.selectedRow = -1
    }
    else {
        self.selectedRow = indexPath.item
    }
    self.collectionView.reloadData()
}
Comments