首页 > 解决方案 > 更改自定义单元格内容视图颜色

问题描述

我在主视图控制器中添加了一个更改主题按钮,其中有一个小表格视图。除了表格视图单元格的内容视图背景颜色外,我可以更改所有颜色,并且无法在 cellForRowAt 之外访问它。

我应该怎么办?有没有办法从我的自定义单元格中触发一个函数来改变颜色?

标签: iosswiftuitableviewcustom-cell

解决方案


您可以在控制器中添加一个属性来确定单元格的颜色。当你想改变颜色时,你打电话给tableView.reloadData(). 这将cellForRowAt在每个可见单元格上调用,您可以在此委托方法中更改颜色。

Your viewController

YourViewController: UIViewController {
    fileprivate var cellColor = UIColor.blue

    // where you change color
    func changeColor() {
        cellColor = UIColor.red
        // this will make the delegate method `cellForRowAt` be called on each visible row
        tableView.reloadData()
    }
}

cellForRowAt:

// delegate method
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuse id", for: indexPath) as! YourCustomCell
    cell.contentView.backgroundColor = cellColor
    // anything else...
    return cell
}

推荐阅读