Search code examples
iosswiftstoryboard

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?


Solution

  • 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