Search code examples
iosswiftuilabel

UILabel not wrapping after the text is changed


enter image description here

I have a UI Label, and I set the numberOfLines to be 0 so it wraps when it needs to.

I have the text changes once in a while. Sometimes it only takes one line, but it truncates instead of wrapping when the text gets too long. The label only wraps if I refresh the table view, calling reloadData().

Is there a way to automatically wrap the label without calling reloadData()?

Before reloading the table view:

enter image description here

After reloading the table view:

enter image description here


Solution

  • When you change the text in a label in a table view cell, the table view does not automatically re-calculate cell sizes.

    To do so, you either reload the data - as you've seen - or, execute these two lines:

    tableView.beginUpdates()
    tableView.endUpdates()
    

    If you are updating the text in the label from inside your cell class, you'' want to use a delegate / protocol pattern to tell the table view controller to execute those two lines.