iosswiftxcodestoryboardcontainer-view

how to manage which controller should show in parent view controller?


I have a parent view controller with 5 container view as you can see in image : enter image description here

but when I run my app ,all child view controllers are shown blow by blow and they dismiss and goes back to my starter view controller (which is initial view controller and I push my parent navigation controller form it). I want to know how to prevent it and how to show my first view controller when parent view controller showed ?


Solution

  • I don't know what is wrong with storyboard but my problem was : because I adde 5 container view to my main view controller and connected all of them to their view controllers by segue it presents all of them and then close main view controller . I clean all segue and container views from storyboard and I did it like this :

    private lazy var firstViewController: AvailableView = {
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            var viewController = storyboard.instantiateViewController(withIdentifier: "AvailableViewID") as! AvailableView
            self.add(asChildViewController: viewController)
    
            return viewController
        }()
    
        private lazy var secondViewController: NotificationView = {
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            var viewController = storyboard.instantiateViewController(withIdentifier: "NotificationViewID") as! NotificationView
            self.add(asChildViewController: viewController)
            return viewController
        }()
    
        private func add(asChildViewController viewController: UIViewController) {
            addChild(viewController)
            view.addSubview(viewController.view)
            viewController.view.frame = view.bounds
            viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            viewController.didMove(toParent: self)
        }
    
        private func remove(asChildViewController viewController: UIViewController) {
            viewController.willMove(toParent: nil)
            viewController.view.removeFromSuperview()
            viewController.removeFromParent()
        }
    

    and the way you can use it : in viewDidLoad():

            add(asChildViewController: firstViewController)
    

    and when you wanted to present second view controller you should remove first View Controller and then add your second view controller like so:

    remove(asChildViewController: firsttViewController)
    add(asChildViewController: secondViewController)
    

    you can see this link for more explanation : https://cocoacasts.com/managing-view-controllers-with-container-view-controllers/

    hope to help any one else :)