Hide or temporarily remove a child ViewController from a parentViewController?

7.7k Views Asked by At

(asking and self-answering, since I found no hits on Google, but managed to find a solution in the end by trial and error)

With iOS 5 and 6, Apple added some ugly hacks to make InterfaceBuilder support "embedded" viewcontrollers. They didn't document how those work, they only give code-level examples, and they only cover a limited subset of cases.

In particular, I want to have an embedded viewcontroller that is sometimes hidden - but if you try the obvious approach it doesn't work (you get a white rectangle left behind):

childViewController.view.hidden = TRUE;
4

There are 4 best solutions below

0
On

Why don't you just create an IBOutlet to your container view and do

self.containerView.hidden = YES;
6
On

How they've done it appears to be a variation on the manual way that worked since iOS 2 (but which only supported views, not viewcontrollers) - there is a real, genuine UIView embedded into the parent (not mentioned in the source code examples - it's only added when you use InterfaceBuilder!).

So, instead, if you do:

childViewController.view.superview.hidden = TRUE;

...it works!

Also, counterintuitively, you can call this method at any time from viewDidLoad onwards - the "embed segue" hack from Apple is executed before viewDidLoad is called.

So you can do this on startup to have your childViewController start off invisible.

2
On

Use This [self.childviewController setHidden:YES];

0
On

In case somebody will need to hide/show all child views or iterate over them:

func hideChildrenViews() {
    for view in self.view.subviews {
        (view as! UIView).hidden = true
    }
}

func showChildViews() {
    for view in self.view.subviews {
        (view as! UIView).hidden = false
    }
}