Search code examples
swiftuiviewcontrolleruikit

How do I put two UIViewController vertically in UIKit?


I want to put two UIViewController in one screen simultaneously in UIKit. However, I couldn't find the solution.

Like this:

enter image description here

I want to display both UINavigationController and Admob Banner in one screen and independently. The one doesn't affect the other.

Could you tell me how to do this?


Solution

  • You want to use view controller containement. The easiest way to do this is as follows.

    Open your storyboard.

    Add a view controller. Let's call it "Parent". Give it a unique identifier.

    Tap the "+" to add a new component to your parent view controller. Search on "Container" and drag 2 container views onto your parent view controller. Those container views will contain the content view of your 2 view controllers. Set up the constraints on those container views so they are laid out top and bottom as you show in your picture.

    Next add view controllers for view controller 1 and view controller 2 to your storyboard. (you can also add links to view controllers from other storyboards, but I'll ignore that.) Lets call those Child1 and Child2.

    Control-drag from each container in Parent onto the child view controller you want to appear in that container. When prompted, select that you want to create an "embed segue".

    An embed segue tells your app that it should load the child view controllers when Parent is loaded, and make their content views subviews of the container views.

    In Parent, the PrepareForSegue() method will fire as each child view controller has been initialized and its view is getting ready to be loaded. At that point you can pass information to the child view controllers, set up delegate links, etc. (Note that you can't, and shouldn't, manipulate the child view controller's view hierarchies directly. Instead, pass data to the child view controllers using proprerties or methods of those view controllers, and have the children's viewDidLoad methods install that data into the views as needed.