When is superview available in an iOS UIViewController?

AndrewThekenAndrewTheken USMember, Beta

Hi All,

I am dealing with an issue where I need to set constraints for a subview to the superview. In the parent controller, I am adding the controller and view on a tap gesture (the parent View has already been presented on screen):

var eventDetail = new EventDetailController (); AddChildViewController (eventDetail); View.AddSubview (eventDetail.View);

In the child view controller's ViewWillAppear, I'd like to add AutoLayout constraints between the View and its Superview, but Superview is null at this point, what gives? When is the View's Superview get set? Is this normal behavior?


  • adamkempadamkemp USInsider, Developer Group Leader mod

    A child view should never handle its own layout. The parent view (the one with the code you quoted) should be setting up those constraints.

  • AndrewThekenAndrewTheken USMember, Beta

    @adamkemp‌ - That makes sense. I'm curious though, should superview be defined at "ViewWillAppear", or is that only guaranteed after "ViewDidAppear"?

  • adamkempadamkemp USInsider, Developer Group Leader mod

    It is undefined whether Superview will have a value in ViewWillAppear. The reasoning is that in ViewWillAppear your view is not yet on the screen, which means it is not yet in a window (if you inspect your Window property then it will be null). However, sometimes your Superview is the window itself so there are certainly times when Superview is also null in ViewWillAppear. However, it can also have a value. For instance you can construct a whole hierarchy of view controllers, adding their views as subviews of other view controllers, etc. and then at the end put the root of that hierarchy on the screen. That is the point at which ViewWillAppear is called, in which case some of those view controllers will already have a Superview.

    So you can't rely on Superview being null or not. It depends. In ViewDidAppear you know you are already on the screen, which means not only is your Superview not null, but your Window is also not null. If you need to do something after you are in the window, but before you are shown to the user, the only place I've found that works is ViewWillLayoutSubviews, which unfortunately is called more often than you would want for that, but it works.

  • AndrewThekenAndrewTheken USMember, Beta

    @adamkemp. Awesome. Thanks for the detailed explanation. This has proven to be exceedingly difficult to track down in the official docs, but makes total sense.

    I appreciate the help.

Sign In or Register to comment.