Child content view controller view has wrong bounds size from Storyboard?

Jeff picture Jeff · Oct 20, 2012 · Viewed 7.3k times · Source

This document outline from my sample Storyboard shows what I'm working with.

document outline

I have a custom container view controller and two content view controllers connected via embed segues.

Here is the storyboard itself.

storyboard summary

ZetaViewController has to create some programmatic views (within ZetaView, of course). I noticed when I was centering these programmatically created views they seemed really off center.

ZetViewController is centering things by examining self.view.bounds.size.height and self.view.bounds.size.width and doing some appropriate arithmetic.

When I added debug logging to ZetaViewController, I noticed that self.view.bounds.size.height and self.view.bounds.size.width had dimensions equal to ContainerView (768 x 1004) and not ZetaView (728 x 637). The Size Inspector in IB confirms these values.

I created a distinctive value for the tag attribute of ZetaView and logged it. ZetaViewController.view really is ZetaView because the tag value confirms it.

So what is going on? Why would ZetaView, shown clearly with smaller dimensions on the Storyboard and in the Size Inspector, show the wrong values in it's properties during run time?

Answer

Jeff picture Jeff · Oct 22, 2012

My problem had nothing to do with Storyboards, segues, or custom container view controllers vs content view controllers. It had to do with the new Cocoa Auto Layout features introduced in iOS 5.

My problem arose from inspecting view bounds size in viewDidLoad instead of in viewWillLayoutSubviews. At the time viewDidLoad is called, the view controller's view has not been given its proper size yet. When I moved the code which programmatically centers views to viewWillLayoutSubviews, it worked as I expected. I still leave view creation code in viewDidLoad because viewWillLayoutSubviews is called repeatedly as layout changes.

See also the View Programming Guide for iOS section "Tweaking the Layout of Your Views Manually".