Cesare
Cesare

Reputation: 9419

Embed multiple view controllers in a container view

I have a base view controller which is like my "blueprint" to create more view controllers to show the user (register/login/reset password/etc.). This base view controller has a container view.

I have many little view controllers that I would like for the container view of my base view controller, like so:

enter image description here

How do I use different view controllers for the container view? How do I specify which mini view controller I can use in my container view? I could probably use the storyboard ID/segues but I don't know how. Any tips?

Upvotes: 8

Views: 8005

Answers (2)

Optimus
Optimus

Reputation: 810

Hi cesare the problem can be resolve by taking the containerView in baseClass where you can take three different viewControllers.

Please find these simple tutorial where you can add or remove the child viewController programmatically

        private func add(asChildViewController viewController: UIViewController) {
            // Add Child View Controller
            addChildViewController(viewController)

            // Add Child View as Subview
            view.addSubview(viewController.view)

            // Configure Child View
            viewController.view.frame = view.bounds
            viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

            // Notify Child View Controller
            viewController.didMove(toParentViewController: self)
        }

        private func remove(asChildViewController viewController: UIViewController) {
            // Notify Child View Controller
            viewController.willMove(toParentViewController: nil)

            // Remove Child View From Superview
            viewController.view.removeFromSuperview()

            // Notify Child View Controller
            viewController.removeFromParentViewController()
        } 

For reference you can find this github project

https://github.com/bartjacobs/ManagingViewControllersWithContainerViewControllers/blob/master/ViewControllerContainment/MasterViewController.swift

Upvotes: 12

Fangming
Fangming

Reputation: 25260

You can only have one embed segue from a container view to another view controller. So the best way is that you can have that one view controller showing dynamic contents.

However, if you prefer to have static view controllers on storyboard, what you can do is to embed a tab bar controller to your container view. You have have all your view controllers as one of the tabs. After that, all you need to do is to first hide the tab bar, then decide which tab to show up using tabBarController.selectedIndex = yourIndex

Upvotes: 2

Related Questions