How can I stop reuse cells from imitating style changes of other cells?

244 views Asked by At

I have a UICollectionView where the cells are given a blue border when tapped. The problem is that when I scroll down to more cells, some of the new cells imitate the blue border without ever having been tapped. Anybody know how to fix this?

Code:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return tradeImages.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: OffersCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell4", forIndexPath: indexPath) as! OffersCollectionViewCell
    tradeImages[indexPath.row].getDataInBackgroundWithBlock{
        (imageData: NSData?, error: NSError?) -> Void in
        if error == nil {
            let image = UIImage(data: imageData!)
            cell.offersImg.image = image
        }
    }
    return cell
}

func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
    var cell = self.collectionView.cellForItemAtIndexPath(indexPath)
    if cell!.tag == 0 {
        cell!.layer.borderWidth = 2.0
        cell!.layer.borderColor = UIColor.blueColor().CGColor
        offersArray.append(objectsArray[indexPath.row] as! PFObject)
        cell!.tag = 1
    } else {
        cell!.layer.borderWidth = 0.0
        cell!.tag = 0
        if let index = find(offersArray, objectsArray[indexPath.row] as! PFObject) {
            offersArray.removeAtIndex(index)
        }
    }
    return true
}
1

There are 1 answers

6
Eendje On BEST ANSWER

Use the method prepareForReuse() in your OffersCollectionViewCell and set the initial values there for your cells for reuse.

For example:

override func prepareForReuse() {
    super.prepareForReuse()

    layer.borderWidth = 0.0
    layer.borderColor = UIColor.whiteColor().CGColor

    // Other initial values
}