0

I'm loading a table view header from a xib file and setting it like this:

self.tableView.tableHeaderView = ... // My header view.

The view loaded from the xib is already the correct size (300 x 50px). When I execute this code in the table view controller's viewDidLoad method the header appears with a height of 0px. When I set it in the viewWillLayoutSubviews method, it appears with the correct height of 50px. In both cases the width is set to the correct width (634px).

I've seen lots of posts about setting the header height and I can get everything working fine by adding it in viewWillLayoutSubviews, but what I have not found is an explanation of why it works in viewWillLayoutSubviews and not viewDidLoad.

Does anyone know why?

As viewDidLoad is executed first, I would have thought adding the header there would be fine.

drekka
  • 20,957
  • 14
  • 79
  • 135
  • In `viewDidLoad`, the frames are not guaranteed to be correct. – saurabh Jan 25 '17 at 06:25
  • In my case the header view contains internal constraints that will generate a height of 50px. The thing I don't understand is why setting the header in viewWillLayoutSubviews respects these constraints where as setting it earlier does not. – drekka Jan 25 '17 at 06:29
  • You have autolayout disabled? – William GP Jan 25 '17 at 06:30
  • Using `Autolayout`, frame of your views are set when the autolayout engine starts its calculation: http://stackoverflow.com/a/17638247/3207014 – saurabh Jan 25 '17 at 06:32
  • @drekka you half-answered yourself. viewDidLoad the view has not yet applied the constrains. This is why in the viewWillLayoutSubviews is the suggested place to make any modification to your views. – pinedax Jan 25 '17 at 06:32
  • Hmm. Perhaps I'm not being clear or understanding what you guys are saying. I understand that layout is done in viewWillLayoutSubviews and not in viewDidLoad. I haven't disabled auto layout. I'm not doing anything with the frames or positioning. I'm merely setting the tableHeaderView property. What I don't understand is why If I set it in viewDidLoad, the height is zero'd when constraints are calculated later on. Even if I do a setNeedsLayout on the header after setting it. It's as if the only way to get the table view to use the height is to set the property in viewWillLayoutSubviews. – drekka Jan 25 '17 at 06:44
  • I understand that viewWillLayoutSubviews is a place for modifying views. Especially sizes, constraints, etc. What I don't get is why adding a header view prior to that would cause the layout calculations to get it wrong. – drekka Jan 25 '17 at 06:46

0 Answers0