Ios 使用导航栏按钮更改集合视图单元格背景

Ios 使用导航栏按钮更改集合视图单元格背景,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我希望有人能在这个编码问题上帮助你。我想用导航栏按钮更改集合视图单元格的背景色,这是我的栏按钮选择器代码: func handleBrightnessChanged() { let readingCell = ReadingsDisplayCell() readingCell.backgroundColor = .red } 但是,当我点击它时,按钮什么也做不了。你能帮帮我吗?以下是我的UICollectionViewCell类: class ReadingsDisplayCell

我希望有人能在这个编码问题上帮助你。我想用导航栏按钮更改集合视图单元格的背景色,这是我的栏按钮选择器代码:

func handleBrightnessChanged() {
   let readingCell = ReadingsDisplayCell()
   readingCell.backgroundColor = .red
}
但是,当我点击它时,按钮什么也做不了。你能帮帮我吗?以下是我的UICollectionViewCell类:

class ReadingsDisplayCell: UICollectionViewCell {

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.gray
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("fatal error in Daily cell")
    }

}

非常感谢。

您正在创建一个新单元格并设置其背景色,这对现有单元格没有影响。要更改单元格的颜色,请执行以下步骤

首先,创建一个属性来跟踪单元格颜色

var currentBackgroundColor = UIColor.gray
handleBrightnessChanged
函数中,将此属性设置为新值

func handleBrightnessChanged() {
    currentBackgroundColor = .red
}
接下来,在
collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)函数中设置单元格的背景色

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myID", for: indexPath)
    cell.backgroundColor = currentBackgroundColor
    return cell
}
要使此更改在按下按钮时生效,请在按下按钮时重新加载集合视图的数据

func handleBrightnessChanged() {
    currentBackgroundColor = .red
    collectionView.reloadData()
}

在运行时,collectionView单元格的背景颜色是否为灰色?非常感谢!正是我要找的。