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

时间:2015-06-09 15:46:27

标签: ios swift uicollectionview

我有一个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
}

1 个答案:

答案 0 :(得分:1)

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

例如:

override func prepareForReuse() {
    super.prepareForReuse()

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

    // Other initial values
}