重新加载集合视图后如何解决 UIButton 边框问题

How to resolve UIButton border issue after reload collection view

我必须为 UIButton 应用边框,其颜色与 UIButton 背景颜色相匹配,它工作正常,但当我重新加载集合视图时,它会应用于其他按钮,然后重新加载它会应用于其他按钮。假设如果集合视图重新加载 3 次,那么它将边框应用到 3 个按钮,这是错误的,它应该只应用那些背景颜色与颜色变量 color

匹配的按钮

注意:- 一次只能有一个按钮有边框。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChromazonColorCell", for: indexPath) as! ChromazonColorCell
    cell.configureData(data: colorSource[indexPath.row])
    cell.cellColorButton.tag = indexPath.row
    if color == colorSource[indexPath.row] {
        cell.cellColorButton.layer.cornerRadius = 5.0
        cell.cellColorButton.clipsToBounds = true
        cell.cellColorButton.layer.borderWidth = 2
        cell.cellColorButton.layer.borderColor = UIColor.black.cgColor
    }
    return cell
}

我认为这对您有用..当您重新加载集合视图时,它将重新使用您的单元格。并且您重复使用的单元格将有边框,因此它也适用于其他单元格。 请尝试以下解决方案

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChromazonColorCell", for: indexPath) as! ChromazonColorCell
  cell.configureData(data: colorSource[indexPath.row])
  cell.cellColorButton.tag = indexPath.row
  if color == colorSource[indexPath.row] {
    cell.cellColorButton.layer.cornerRadius = 5.0
    cell.cellColorButton.clipsToBounds = true
    cell.cellColorButton.layer.borderWidth = 2
    cell.cellColorButton.layer.borderColor = UIColor.black.cgColor
  }
else{
    cell.cellColorButton.layer.cornerRadius = 5.0
    cell.cellColorButton.clipsToBounds = true
    cell.cellColorButton.layer.borderWidth = 0
    cell.cellColorButton.layer.borderColor = UIColor.clear.cgColor
}
 return cell
}

Dixit Rathod 已回答。

而且,您可以在您的单元格:

中使用您的代码和prepareForReuse方法
func prepareForReuse(){ 
    super.prepareForReuse()

    cellColorButton.layer.cornerRadius = 0.0
    cellColorButton.clipsToBounds = true
    cellColorButton.layer.borderWidth = 0
    cellColorButton.layer.borderColor = UIColor.clear.cgColor
}