How to remove the ChildViewController from Parent View Controller in Swift 3

childViewControllers.forEach({
  $0.willMove(toParentViewController: nil)
  $0.view.removeFromSuperview()
  $0.removeFromParentViewController()
})

This answer is for swift 4.2 and above one is less than 4.2 versions.

children.forEach({
  $0.willMove(toParent: nil)
  $0.view.removeFromSuperview()
  $0.removeFromParent()
})

Here is the more concise version for removing all child controllers from the parent. You can use self.childViewControllers to define explicitly. As this approach, you can get rid of these extra conditions to check.


After the long search to remove the view controllers from viewpager. I did it in the following way.

 if self.childViewControllers.count > 0{
        let viewControllers:[UIViewController] = self.childViewControllers
        for viewContoller in viewControllers{
            viewContoller.willMove(toParentViewController: nil)
            viewContoller.view.removeFromSuperview()
            viewContoller.removeFromParentViewController()
        }
    }

here self is , Current UIViewController which has View Pager. I need to remove all the childview controllers from the view pager. So, i get the list of view controllers from Current UIViewController. Then i removed it from the Parent view.

For swift 4.2

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

EDIT

Remove top childview controller:

   func removeTopChildViewController(){
         if self.children.count > 0{
             let viewControllers:[UIViewController] = self.children
                viewControllers.last?.willMove(toParent: nil)
                viewControllers.last?.removeFromParent()
                viewControllers.last?.view.removeFromSuperview()
         }
     }

Swift 4.2 and above

create extension on UIViewController and add removeChild() method

extension UIViewController {
        
  func removeChild() {
    self.children.forEach {
      $0.willMove(toParent: nil)
      $0.view.removeFromSuperview()
      $0.removeFromParent()
    }
  }
} 

Usage:

call removeChild from parent UIViewController

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.removeChild()
}

Tags:

Ios

Xcode

Swift3