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

标签 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
}

最佳答案

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

例如:

override func prepareForReuse() {
    super.prepareForReuse()

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

    // Other initial values
}

关于ios - 如何阻止重用单元格模仿其他单元格的样式更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30736876/

相关文章:

ios - 如何为不同的 xAxis 标签呈现自定义标签颜色?

ios - 我如何阻止 ios 自动将 cookie 添加到我的 NSMutableURLRequest

iphone - 如何在 iOS 中将 UIImage 保存为渐进式 JPEG 格式?

ios - 在运行时增加 tableview 高度以包含全部内容

swift - 如何从 Swift 中的字符串中删除变音符号?

ios - 捏缩放后保持 collectionView 单元格位置

ios - 设置单元格数据后如何更新 UICollectionView 中单元格的大小?

ios - 如何在 Swift 中禁用 Collection View 中的特定单元格

ios - Xcode 10 build 10A255 需要清理构建文件夹以进行所有更改

iphone - 调整 View 大小。没有按我计划的方式工作