简体   繁体   中英

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.

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() . This will make cellForRowAt be called on each visible cell, and you can change color in this delegate method.

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来实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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