0

I have 2 labels on the cell. If the labels show just one line of text, then the cell looks fine. But if there is more text and if the lines on the labels are wrapped up, then the labels/text on it goes outside of the cell. Attaching image.

enter image description here

My current code:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {      
    return 68.0
}

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     // Code to dequeue reusable cell.
    
            self.titleLabel.text = "This is a very very long text for the title label. Testing testing"
            self.subTitleLabel.text = "This is a very very long text for the sub title label. Testing testing the wrapping"
            
            self.titleLabel.sizeToFit()
            self.titleLabel.layoutIfNeeded()
            
            self.subTitleLabel.sizeToFit()
            self.subTitleLabel.layoutIfNeeded()
    }

Solution I tried to fix it:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {      
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     // Code to dequeue reusable cell.

            self.titleLabel.text = "This is a very very long text for the title label. Testing testing"
            self.subTitleLabel.text = "This is a very very long text for the sub title label. Testing testing the wrapping"

            self.titleLabel.sizeToFit()
            self.titleLabel.layoutIfNeeded()

            self.subTitleLabel.sizeToFit()
            self.subTitleLabel.layoutIfNeeded()
    }

override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.estimatedRowHeight = 500
        self.tableView.rowHeight = UITableView.automaticDimension
}

This is how it looks with the solution. How do I update the height of the cell based on it's contents?

enter image description here

tech_human
  • 6,592
  • 16
  • 65
  • 107
  • 2
    Does this answer your question? [Using Auto Layout in UITableView for dynamic cell layouts & variable row heights](https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights) – Kirow Apr 21 '21 at 12:02
  • did you set `titleLabel` and 1subTitleLabel` height constraint ? ?? – Ekramul Hoque Apr 21 '21 at 12:07
  • PLease set height of Labels. This will fix your problem. – Kudos Apr 21 '21 at 12:45

1 Answers1

0
  1. set number of lines to zero. apply proper constraints.

  2. second solution put the labels in stackView and number of lines of both labels to zero.

Manish Kumar
  • 997
  • 2
  • 13
  • 30