【问题标题】:Change Collection View Cell background with navigation bar button Swift使用导航栏按钮 Swift 更改集合视图单元格背景
【发布时间】:2017-11-06 22:09:05
【问题描述】:

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

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")
    }

}

非常感谢。

【问题讨论】:

  • 在运行时,collectionView 单元格的背景颜色是灰色的吗?

标签: ios swift uicollectionview


【解决方案1】:

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

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

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()
}

【讨论】:

  • 非常感谢!正是我想要的。
猜你喜欢
  • 2019-10-24
  • 2013-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多