Ios – How to change the height of a UITableView to fit its dynamic content

iosuitableview

I've a UITableView which contains a cell, which in turn contains a TTTextEditor (a Three20 control) which for all intents and purposes is a UITextView. I'm using the TTTextEditor so the user can enter a dynamic amount of text, and as the control resizes I'm using a delegate method to increase the height of the containing cell accordingly. So far so good.

When I've finished editing, with the cell now taller, the table no longer scrolls enough to cover the content. I'm assuming I need to adjust the height of the table to compensate for the increase in the cell height, but whatever I try doesn't seem to have an effect. From reading around, I'm trying this:

CGRect frame = [self.tableView frame];
CGSize contentSize = self.tableView.contentSize;

[self.tableView setFrame:CGRectMake(frame.origin.x, 
                                    frame.origin.y, 
                                    frame.size.width, 
                                    contentSize.height)];

But it doesn't work – the frame height does increase, but not to the correct height, and in any case the table scrolls no more that it did originally. I've also tried the sizeToFit method on the tableView without success.

Does anyone have an insight into how I can get the tableview's scrollable height to increase?

Best Answer

You need to set the contentSize not the frame. Calculate what the size SHOULD be, and then set it. This may require some calculation on your part. If you're dealing with text, then you may want to look at the method added to NSString called sizeWithFont:constrainedToSize:lineBreakMode:. Your frame, on the other hand, should always be the size of the viewable area, NOT the scrollable area.

EDIT: Note that for the initial layouts that are not changing at that moment, you will probably want to use the standard table delegate mechanism of - (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath, but when that needs to change dynamically like this situation, I think adjusting the content size is worth a try.