简体   繁体   English

更改自定义单元格内容视图的颜色

[英]Change custom cell content view color

I added a change theme button in my main view controller where I have a tiny table view. 我在主视图控制器中添加了一个更改主题按钮,其中有一个很小的表视图。 I can change every color except a table view cell's Content View background color, and I can't access it outside cellForRowAt. 我可以更改表格视图单元格的“内容视图”背景色以外的所有颜色,并且不能在cellForRowAt之外访问它。

What should I do? 我该怎么办? Is there anyway to trigger a function from my custom Cell to change the color? 无论如何,有没有从我的自定义单元格触发功能来更改颜色的功能?

You can add a property in your controller to determine the color of the cells. 您可以在控制器中添加属性以确定单元格的颜色。 When you wanna change the color, you call tableView.reloadData() . 要更改颜色时,请调用tableView.reloadData() This will make cellForRowAt be called on each visible cell, and you can change color in this delegate method. 这将使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
}

如果您具有自定义单元格类并访问委托方法以更改内容视图的颜色,则可以通过实现delegate来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM