如何阻止重用单元格模仿其他单元格的样式更改?

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

我有一个 UICollectionView,其中的单元格在点击时会显示蓝色边框。问题是,当我向下滚动到更多单元格时,一些新单元格模仿蓝色边框而从未被点击过。有人知道如何解决这个问题吗?

代码:

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
}

在您的 OffersCollectionViewCell 中使用方法 prepareForReuse() 并在那里为您的单元格设置初始值以供重复使用。

例如:

override func prepareForReuse() {
    super.prepareForReuse()

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

    // Other initial values
}