Search code examples
iosswiftuitableviewcell

Change background of Cell in UITableView


I want to change the background color of a specific cell to match the color of the text. For example, the "Red" cell would have a red background and so on. Im having difficulty in figuring out what code to place. Any suggestions?

import UIKit

class PedsTableViewController: UITableViewController {
    var PENames = [String] ()
    var PEIdentities = [String] ()
    var PEDetail = [String] ()

    override func viewDidLoad() {
        PENames = ["Green","Orange","Blue","White","Yellow","Purple","Red","Pink"]
        PEIdentities = ["Green","Orange","Blue","White","Yellow","Purple","Red","Pink"]
        PEDetail = ["Green","Orange","Blue","White","Yellow","Purple","Red","Pink"]
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return PENames.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PECell")

        cell?.textLabel!.text = PENames[indexPath.row]

        cell?.detailTextLabel!.text = PEDetail[indexPath.row]


        return cell!
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let vcName = PEIdentities[indexPath.row]
        let viewController = storyboard?.instantiateViewController(withIdentifier: (vcName))
        self.navigationController?.pushViewController(viewController!, animated: true)

    }
}

Solution

  • You can create a new array with matching colors:

    var colors = [UIColor]()
    
    override func viewDidLoad() {
      colors = [.green, .orange ... ]
    }
    

    Then, just set the color in the cell:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "PECell")
    
      ..
    
      cell?.contentView.backgroundColor = colors[indexPath.row]
      return cell!
    }