Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell my UITableViewCell to "auto-resize" when its content changes?

Tags:

ios

swift

In my cell.xib, I have a label, with constraints to all its sides. I've set that label to lines = 0 and line-break = word wrap. Then, I do this to my TableView:

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 100.0

Everything works great, and my UITableViewCell is auto-height. If the text is long, then my tableView intelligently calculates the size.

The problem is -- how do I tell my UITableView to "re-calculate" the size once the content changes in the cell?

My cell could call its delegate, and in this delegate, I'd like the TableView to re-draw the height.

Right now, the content in my cells change constantly, but the cell height never changes.

like image 658
TIMEX Avatar asked Mar 13 '16 20:03

TIMEX


4 Answers

There is a documented way to do this. See UITableView.beginUpdates() documentation:

You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell.

So, the correct solution is:

tableView.beginUpdates() tableView.endUpdates() 

Also note that there is a feature that is not documented - you can add a completion handler for the update animation here, too:

tableView.beginUpdates() CATransaction.setCompletionBlock {    // this will be called when the update animation ends }  tableView.endUpdates() 

However, tread lightly, it's not documented (but it works because UITableView uses a CATransaction for the animation).

like image 184
Sulthan Avatar answered Nov 05 '22 08:11

Sulthan


I've found the best way to get it to check heights is to call, after whatever text change has been made, in order:

self.tableView.beginUpdates() self.tableView.endUpdates() 

This causes the tableView to check heights for all visible cells and it will cause changes to be made as needed.

like image 37
sschale Avatar answered Nov 05 '22 08:11

sschale


I think the simplest solution is to reload that specific cell. For example:

- (void)yourDelegateMethodOfCell:(UITableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    //If cell is not visible then indexPath will be nil so,
    if (indexPath) {
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}
like image 21
Muhammad Zeeshan Avatar answered Nov 05 '22 08:11

Muhammad Zeeshan


You can get automatic cell height by this code

tableView.beginUpdates()
// add label text update code here 
// label.numberOfLines = label.numberOfLines == 0 ? 1 : 0
tableView.endUpdates()

Below is the reference to this solution with demo :

GitHub-RayFix-MultiLineDemo

like image 37
Vinay Jain Avatar answered Nov 05 '22 08:11

Vinay Jain