Search code examples
swiftuipageviewcontrollerchildviewcontroller

Remove child view controller


I have the following code:

func setUpPageController(viewControllers: [UIViewController]) {
        let pagingViewController = PagingViewController(viewControllers: viewControllers)
        pagingViewController.menuInsets = UIEdgeInsets(top: 1, left: 0, bottom: 1, right: 0)
        pagingViewController.menuItemSize = .selfSizing(estimatedWidth: 100, height: 40)
        pagingViewController.menuBackgroundColor = UIColor.Custom.secondaryColor_white
        pagingViewController.selectedTextColor = UIColor.Custom.secondaryColor_black
        pagingViewController.menuHorizontalAlignment = .center
        pagingViewController.textColor = UIColor.Custom.secondaryColor_black
        
        // Make sure you add the PagingViewController as a child view
        // controller and contrain it to the edges of the view.
        addChild(pagingViewController)
        view.addSubview(pagingViewController.view)
        pagingViewController.view.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            pagingViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
            pagingViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            pagingViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            pagingViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        ])
        
        pagingViewController.didMove(toParent: self)
    }

I would like to call the function again but instead removed the child view controller before adding another child on top. Because the second time there are different view controllers the would have been added or just a different array all together.

if I leave as is when I call the method again the previous child added shows at the end or beginning of scrolling edge.


Solution

  • This is to make it modular.

    To remove a single child:

    func removeViewController(_ viewController: UIViewController) {
        // this is to notify the the child that it's about to be removed
        viewController.willMove(toParent: nil)
        // this is to remove the child's view from its superview
        viewController.view.removeFromSuperview()
        // this is to remove the child vc from its parent vc
        viewController.removeFromParent()
    }
    

    To remove all children:

    func removeAllChildren() {
        if self.children.count > 0 {
            let childrenVC: [UIViewController] = self.children
            for chlidVC in childrenVC {
                chlidVC.willMove(toParent: nil)
                chlidVC.view.removeFromSuperview()
                chlidVC.removeFromParent()
            }
        }
    }