1

I have an UITableViewCell with UILabel which correctly resizes its height according to text length. To accomplish this I have correctly set AutoLayout constraints and specified

tableView.rowHeight = UITableViewAutomaticDimension

The problem I am having is when the test of the UILabel gets longer after pressing a UIButton - READ MORE, in the cell itself. I programmatically add text to the UILabel and I expect the cell height to grow. I have added:

    self.layoutIfNeeded()
    self.updateConstraints()

in the cell, but it is not working. Cell stays same height.

I have also forced a reload of the cell row in the delegate UIViewController but it is not working either. Am I missing something basic here?

EDIT: The question differ from other similar questions, because I'd like the answer to avoid having to calculate the height manually. Since AutoLayout is perfectly able to calculate correct dynamic height at first load, I guess there should be a way to make it redraw the cell once the text in the label gets longer, without the need of performing manual calculation to estimate row height.

Fabrizio Prosperi
  • 1,398
  • 4
  • 18
  • 32
  • do one thing, bind IBOutlet of UILabel Height and then update that constant.it will work – Anjali Bhimani Jul 26 '16 at 11:00
  • Possible duplicate of [Changing the height of a dynamic-height UITableViewCell after it's already appeared](http://stackoverflow.com/questions/35142584/changing-the-height-of-a-dynamic-height-uitableviewcell-after-its-already-appea) – fishinear Jul 26 '16 at 12:52
  • This is same question, but the answer there is not what I am asking, I don't want to calculate the height myself, nor the estimated height. I want to force an AutoLayout redraw. – Fabrizio Prosperi Jul 26 '16 at 13:18

2 Answers2

2
Get the Label height dynamically and set the tableviewcell height

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   // Calculate the Label height and add it to default height of the cell
}
Nattudurai
  • 856
  • 7
  • 9
  • 1
    Actually this is not the way I want to proceed, the cell height is calculated automatically by AutoLayout in the first place, and should be done also the second time, kind of a redraw. – Fabrizio Prosperi Jul 26 '16 at 13:17
2

I have found a solution that works, after updating the UILabel content I am calling:

 UIView.animateWithDuration(0.3) {
     cell.contentView.layoutIfNeeded()
 }

To update cell constraints. And then to resize the cell height:

 tableView.beginUpdates()
 tableView.endUpdates()

I will wait to accept this answer to see if someone else will answer a more elegant solution though.

Fabrizio Prosperi
  • 1,398
  • 4
  • 18
  • 32