Search code examples
iosswiftuikit

How can I set the properties of a custom created cell with UIListContentConfiguration?


I have created a custom cell, the file for this custom cell is an .xib file (called MessageCell.xib). The .xib file is associated with a .swift file where I can enter the code and in this file I have some IBOutlet properties. What I want to do is to set these properties using UIListContentConfiguration and I don't know how to do it or if it can be set. In the picture below I have implemented this for iOS 14 and later, for older versions I have followed the traditional way. There is nothing wrong with what is written for older versions, but the code I wrote for iOS 14 does not work / gives errors.

This is my specially created cell.

class MessageCell: UITableViewCell {

    @IBOutlet weak var rightImageView: UIImageView!
    @IBOutlet weak var leftImageView: UIImageView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var messageBubble: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        messageBubble.layer.cornerRadius = messageBubble.frame.height / 5
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
    
}

Here I assign a string expression from the messages array to the label property in my cell.

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: K.cellIdentifier, for: indexPath) as! MessageCell
        if #available(iOS 14.0, *)
        {
            var config = cell.defaultContentConfiguration()
            config.text = messages[indexPath.row].body
            cell.contentConfiguration = config
        }
        cell.label.text = messages[indexPath.row].body
        return cell
    }

I achieved many features of the structure through trial and error, but I could not achieve my goal.


Solution

  • You cannot use a UIListContentConfiguration for this, because the interface elements you are trying to configure in the cell are not the built-in image-and-title views. You will have to write a custom UIContentConfiguration and UIContentView, responding in the code to the setting of the properties of the configuration by configuring the corresponding interface elements yourself.