Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UITableViewCell Height on Orientation Change

I have a UITableView with cells containing variable-height UILabels. I am able to calculate the minimum height the label needs to be using sizeWithFont:constrainedToSize:lineBreakMode:, which works fine when the table view is first loaded. When I rotate the table view the cells become wider (meaning there are fewer lines required to display the content). Is there any way I can have the height of the cells redetermined by the UITableView during the orientation change animation or immediately before or after? Thank you.

like image 663
Peter Zich Avatar asked Apr 27 '10 01:04

Peter Zich


2 Answers

Your UITableViewController can implement the tableView:heightForRowAtIndexPath: method to specify the row height for a particular row, and it can look at the current orientation ([[UIDevice currentDevice] orientation]) to decide what height to return.

To make sure tableView:heightForRowAtIndexPath: gets called again when the orientation changes, you'll probably need to detect the orientation change as described in this question, and call [tableView reloadData].

like image 127
David Gelhar Avatar answered Oct 19 '22 01:10

David Gelhar


To improve slightly on the answer above from @David and to answer the last comment about how to animate it smoothly during a rotation, use this method:

- (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

and of course the height delegate method:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return 171.0f;
    } else {
        return 128.0f;
    }
}
like image 25
bandejapaisa Avatar answered Oct 19 '22 00:10

bandejapaisa