others-change text color programmatically when using custom tableviewcell in tableviewcontroller

1. Purpose

In this post, I would demo how to change text color programmatically when using custom tableviewcell in tableviewcontroller.

2. Environment

  • Mac OS 10.15
  • Swift 5
  • Xcode 12

3. The solution

Here is the code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier2", for: indexPath) as! MessageTableViewCell
        if messages.count>0 {
            let msg = messages[indexPath.row]
            cell.body?.text = msg.body
            cell.fromAddress?.text = msg.fromAddress
            let theDate = msg.recvDate
            if let interval = timeIntervalFormatter.string(from: theDate, to: Date()) {
                cell.recvDate?.text = "\(interval)\(agoString)"
            }else {
                cell.recvDate?.text = nil
            }
            if msg.isUnread {
                cell.body.font = UIFont.boldSystemFont(ofSize: 13.0)
            }else {
                cell.body.font = UIFont.systemFont(ofSize: 13.0)
            }
            
            if msg.isStar {
                cell.body.textColor = UIColor.blue
            }else {
                cell.body.textColor = UIColor.black
            }

        }else {
            cell.body?.text = nil
            cell.fromAddress?.text = nil
            cell.recvDate?.text = nil
            cell.recvDate?.text = nil
        }
        return cell
    }

The key point is as follows:

     if msg.isStar {
     		cell.body.textColor = UIColor.blue
     }else {
     		cell.body.textColor = UIColor.black
     }

Now it works!

4. Summary

In this post, I demonstrated how to change the color of text in custom tableviewcell with swift.

-->