4

I have problems with auto layout and the UITableView header (tableHeaderView) in iOS 8.X e iOS7.x.

The self.HeaderView is a XIB built using auto layout. It's used inside a scrollviewer followed by other views and the result is correct.

Then I set it as header of a table view (as described here):

self.tableView.tableHeaderView = self.HeaderView;
[self.HeaderView setNeedsLayout];
[self.HeaderView layoutIfNeeded];
CGSize headerViewSize = [self.HeaderView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGRect frame = self.HeaderView.frame;
frame.size.height = headerViewSize.height;
self.HeaderView.frame = frame;
self.tableView.tableHeaderView = self.HeaderView;

but the resulted height is bigger than expected. I can't understand why. Constraints seem to be ok otherwise why in the scrollview the result is correct?

If in the IB I resize the height of the container frame the constraints are updated without any ambiguity.

Why the UILayoutFittingCompressedSize doesn't compress the view?

#update

I discovered the problem. Basically the constraints are correct.

After layoutSubviews has been called the UIImageView is correctly sized. Width and height are as expected. The problem is in the way systemLayoutSizeFittingSize:UILayoutFittingCompressedSize works.

Instead of calculating the size using the UIImageView size (which has been correctly resized), it uses the size of UIImage (which source file is bigger)

So, what can I do to force systemLayoutSizeFittingSize:UILayoutFittingCompressedSize to calculate the size using the UIImageView size??

Community
  • 1
  • 1
Daniele
  • 143
  • 1
  • 14

2 Answers2

1

Found the solution.

In few words, constraints were ok, on iOS 8 the systemLayoutSizeFittingSize:UILayoutFittingCompressedSize was working as expected but it didn't on iOS7.

For a pure coincidence I called the combination of

[self.HeaderView setNeedsLayout];
[self.HeaderView layoutIfNeeded];

twice and I noticed that in that way the systemLayoutSizeFittingSize:UILayoutFittingCompressedSize worked on iOS 7 too.

In that moment I realized that the solution was calling the combination above twice in sequence (not necessary on iOS 8)

It would be nice to understand why...

Daniele
  • 143
  • 1
  • 14
-1

Here's what I do: I create constraints for the header view to make its left and right equal to the tableview, with a priority of UILayoutPriorityDefaultHigh. I add these constraints to the tableView when the header view moves to a non-nil window in didMoveToWindow: and remove them when it gets removed from its superview in willMoveToSuperview. And once it is set up, I use systemLayoutSizeFittingSize but pass in self.frame, and then I set it as the tableHeaderView.

That seems to work fine, including with rotation. The order of adding/removing constraints is quite important to avoid warnings by UILayout.

gnasher729
  • 51,477
  • 5
  • 75
  • 98