Custom UI TableViewCell selected backgroundcolor swift

前端 未结 11 951
盖世英雄少女心
盖世英雄少女心 2020-12-28 16:51

I am trying to change the appearance of a custom selected TableViewCell using Swift.

Do I need to do it via the designer or programmatically?

I tried the fol

11条回答
  •  旧巷少年郎
    2020-12-28 17:18

    To keep your code clean you should think about moving screen design related code for your cells from UITableViewController into a UITableViewCell class.

    Your UITableViewController` needs only to set the selected state of the cell as follows:

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        guard let cell = tableView.cellForRow(at: indexPath) else { return }
        cell.setSelected(true, animated: true)
    }
    

    Your desired customisation can be implemented in a derrived UITableViewCell class by overriding var isSelected. With this solution you could have even different select colors for each cell.

    class MyTableViewCell: UITableViewCell
    {
        @IBOutlet weak var label:UILabel!
    
        override var isSelected: Bool
        {
            didSet{
                if (isSelected)
                {
                    self.backgroundColor = UIColor.red
                    if let label = label
                    {
                        label.textColor = UIColor.white
                    }
                }
                else
                {
                    self.backgroundColor = UIColor.white
                    if let label = label
                    {
                        label.textColor = UIColor.black
                    }
                }
            }
        }
    }
    

提交回复
热议问题