简体   繁体   中英

Changing UILabel text length in UITableViewCell with dynamic height does not resize it correctly

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.

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM