【问题标题】:Change background of Cell in UITableView在 UITableView 中更改单元格的背景
【发布时间】:2019-04-21 21:46:58
【问题描述】:

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

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

    }
}

【问题讨论】:

    标签: ios swift uitableview cell


    【解决方案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!
    }
    

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    试试看

    let selectedColor: UIColor = .red
    
    cell?.backgroundColor = selectedColor
    

    【讨论】:

    • 虽然我想到了这一点,但它不允许我为每个单元格自定义颜色。只有整张桌子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多