Error404 Error404 - 1 year ago 181
Swift Question

How can I switch between two child View Controllers on Swift?

I am trying to switch between two child

View Controllers
on a particular
Container View
. I have a
Navigation Controller
with a menu (
Table View
to make the different options of the menu).

Each time I click an option of the menu I would like to change the child of the
Container View
but I am getting the child above
Navigation bar
Table View
(they are not shown but they are under the new child View Controller).

The scheme of my Main.storyboard is like this:

Navigation Controller --> View Controller (With 2 Container View, 1 for Table View
and the other to set master View Controller)
| |
View Controller Table View
(id: master)

View Controller (id: Home) View Controller (id: screen2)

I have the following code on
function (in which I detect when an option of the menu is clicked) to change the child View Controller of the Container View:

let currentController = self.navigationController?.visibleViewController //container

var oldChild = (currentController?.childViewControllers.last!)! as UIViewController //master
let newChild = (storyboard?.instantiateViewControllerWithIdentifier("Home"))! as UIViewController //Home

if (oldChild != newChild){
if currentController.childViewControllers.last != nil{


This code is working almost well. The problem is that the new child View Controller is being shown above the Navigation bar and the Table View (the menu). So it is occupying the full screen instead of fit on the Container View.

Should I add something more to my code or am I using my code in a wrong way? I have searched a lot about it but most of the solutions are in objective-c or does not work for me.

EDIT: After searching for a lot of hours I suspect that it is something related with the embeded segue that connects the root
View Controller
View Controller but I am not able to embed the new child to the
Container View
. The code that I am trying is:

currentController.performSegueWithIdentifier("EmbedSegue", sender: newChild)


currentController.presentViewController(newChild, animated: true, completion: nil)

but none of them embed the segue. Just display the
on the full screen.

Thanks in advance!

Answer Source

You should have the IBOutlet for ContainerView and addSubview to this IBOutlet



currentController.addSubview(childView.view, toView: self.containerView)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download