I am overloading the delegate method -tableView:heightForRowAtIndexPath:
and using -sizeWithFont:constrainedToSize:
to programmatically set the height of the cell, based on the text in that cell:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.section) {
case(kAboutViewOverviewSection): {
switch (indexPath.row) {
case(kAboutViewOverviewSectionRow): {
NSString *text = NSLocalizedString(@"kAboutViewOverviewSectionFieldText", @"");
CGSize s = [text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(280, 500)];
return s.height + 13;
}
default: {
break;
}
}
break;
}
default: {
break;
}
}
return 44.0;
}
This works when the table is first drawn. However, when I change the orientation of the device, from portrait to landscape, the cell height does not change.
I tried overriding the -shouldAutorotateToInterfaceOrientation:
method in my table view controller:
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
[self.tableView reloadData];
return YES;
}
This should reload the table data and (presumably) redraw the table cell views. But this does not have any effect.
Is there a way to force a cell to redraw with a new height, when the device is rotated?
EDIT: I have tried the following, to no effect:
- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
[self.tableView reloadData];
}
Here is what the application looks like in portrait orientation:
Here is what the application looks like in landscape orientation:
There is a gap between the top and bottom edges of the content.
EDIT 2:
Adjusting the size parameter via the table frame's width helped fix this display issue:
CGSize s = [text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake([tableView frame].size.width,500)];
It's less than optimal, but the simplest solution is to call -reloadData
on the table.
A better solution would be to call -beginUpdates
, -deleteRowsAtIndexPaths:withRowAnimation:
, -insertRowsAtIndexPaths:withRowAnimation:
, and -endUpdates
or simply -reloadSections:withRowAnimation:
if targeting 3.0 only. This will add animation.
Edit: And you will also need a proper tableView:heightForRowAtIndexPath:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGSize textSize = [[self textForRowAtIndexPath:indexPath] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake([tableView frame].size.width - 20, 500)];
return textSize.height + 13.0f;
}
(where textForRowAtIndexPath:
is a method that returns the cell's text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With