7

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?

Wayne Hartman
  • 18,369
  • 7
  • 84
  • 116
  • It looks like your cell contains multi-line UILabels. In order to get the correct height, the labels will need the `preferredMaxLayoutWidth` property set correctly to the available width (which likely differs when the device is rotated). If you haven't already seen this post, check it out as well as the sample project on GitHub in the comments: http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-heights – smileyborg Oct 20 '13 at 19:10
  • Do you create extra code and put any control in it?can you add your code here? – Banker Mittal Dec 17 '13 at 13:14

1 Answers1

3

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];
Robasan
  • 155
  • 10