在UITableView中更改单元格的背景

时间:2019-04-21 21:46:58

标签: ios swift uitableview cell

我想更改特定单元格的背景颜色以匹配文本的颜色。 例如,“红色”单元格将具有红色背景,依此类推。 我很难弄清楚要放置什么代码。有什么建议吗?

导入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)

    }
}

2 个答案:

答案 0 :(得分:1)

您可以创建具有匹配颜色的新数组:

var colors = [UIColor]()

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

然后,只需在单元格中设置颜色:

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

  ..

  cell?.contentView.backgroundColor = colors[indexPath.row]
  return cell!
}

答案 1 :(得分:0)

只需尝试

let selectedColor: UIColor = .red

cell?.backgroundColor = selectedColor