Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tableview:heightForRowAtIndexPath: Incorrect reporting content view size with AutoLayout

I have a UITableViewCell with a custom label using AutoLayout. It's constraints are set with a constant leading, trailing, bottom, and top space to the content view. The table view controller that these cells appear in is inside a UISplitViewController. When the table view is loaded, I calculate the height of the cell using the following code:

CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGFloat height = size.height;

In portrait this allows me to properly display the cell. Here is a screenshot of part of the cell:

enter image description here

However, when I rotate the iPad into landscape, it is not calculating the correct size and end up with too much padding:

enter image description here

Setting a breakpoint when the tableview:heightForRowAtIndexPath: is called when rotated the size of the content view is not being reported properly. In fact it is reporting the old, narrower size of the table view.

How do I get my cells to resize appropriately with UISplitViewController on iPad?

like image 704
Wayne Hartman Avatar asked Oct 14 '13 02:10

Wayne Hartman


1 Answers

UILabel#preferredMaxLayoutWidth affects systemLayoutSizeFittingSize. For example. You could place UILabel on the View with Interface Builder.

Label Layout

  • The width of superview is 320px.
  • The horizontal space constraints of UILabel are 20px.

In this case UILabel#preferredMaxLayoutWidth will be set 280px. systemLayoutSizeFittingSize will return the width that is not over 320px even if frame.width of Superview was 480px.

One of the solution is to override CustomCell#setFrame method.

- (void)setFrame:(CGRect)frame {  
     [super setFrame:frame];  
     _label.preferredMaxLayoutWidth = frame.size.width - 20*2 /*Horizontal Spacing*/;   
}

And then you need to update layout when you update the label.text.

_customCell.label.text = @"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
[_customCell setNeedsLayout];
[_customCell layoutIfNeeded];
like image 187
Robasan Avatar answered Sep 28 '22 15:09

Robasan