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
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
}
}
}
}
}