In my app I have a table view with customised table view cells. In iOS5 i use the following snippet of code to get the correct height for my customised cells. In iOS6 after doing a [tableView reloadData] the [cell layoutIfNeeded] will not trigger the cells layoutSubViews method. And because of that the cells heights are wrongly calculated. Any good suggestions to why this is? Or maybe alternative ways of doing it?

- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:aTableView cellForRowAtIndexPath:indexPath];
    [cell setNeedsLayout];
    [cell layoutIfNeeded];
    [cell sizeToFit];

    return cell.frame.size.height;
}
有帮助吗?

解决方案

Your code snippet has fundamental errors regarding table view life cycle. If it works on iOS 5 or anywhere as you claimed, you might just being lucky.

First of all, tableView:heightForRowAtIndexPath: is called BEFORE tableView:cellForRowAtIndexPath:. At this point, NO cell exists. You are not supposed to call UITableViewCell *cell = [self tableView:aTableView cellForRowAtIndexPath:indexPath]; here.

For laying out subviews of tableView (suppose it is the top level view of view controller), you could override viewWillLayoutSubviews method of view controller. That's what Apple recommends.

For laying out subviews of table view cell, you could subclass UITableViewCell and override its layoutSubviews method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top