How to dynamically resize UITableViewCell height

IphoneUitableviewResizeUitextview

Iphone Problem Overview


I have the classical grouped UITableView with editable UITextViews inside every cell. This text views can be single or multi-lined, and I want the cell to increase its height as the user writes and the text starts a new line.

My question is: do I need to reload the whole table just to increase the height of a cell? Isn't there any other method?

I've been searching a lot, and previous answers and tutorials just talk about how to calculate text height, how to implement heightForRowAtIndexPath... things that I already know. My concern is that, to achieve what I want, I will have to calculate height and reload the table every time the user enters a new character, which I don't find very clean or efficient.

Thanks.

Iphone Solutions


Solution 1 - Iphone

[tableView beginUpdates];
[tableView endUpdates];

Solution 2 - Iphone

You do not always have to reload the entire table. You can instead just reload that one row.

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];

Solution 3 - Iphone

To be more specific, yes, you have to implement tableView:heightForRowAtIndexPath: to calculate the new height, then do as rickharrison says and call [tableView reloadRowsAtIndexPaths:withRowAnimation]. Lets say your cells can have an expanded height and a normal height, and you want them to grow when tapped on. You can do:

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath 
{
    if ([expandedPaths containsObject:indexPath]) {
        return 80;
    } else {
        return 44;
    }
 }

-(void)tableView:(UITableView*) didSelectRowAtIndexPath:(NSIndexPath*) indexPath
{
    [expandedPaths addObject:indexPath];
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

Solution 4 - Iphone

-reloadRowsAtIndexPaths:withRowAnimation did not resize the UITableViewCell height, even after I changed the Cell's frame. It only worked when I followed it with a -reloadData:

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
[tableView reloadData];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaraidView Question on Stackoverflow
Solution 1 - IphoneAndrey ZverevView Answer on Stackoverflow
Solution 2 - IphonerickharrisonView Answer on Stackoverflow
Solution 3 - IphoneElfredView Answer on Stackoverflow
Solution 4 - IphonewindsonView Answer on Stackoverflow