Search code examples
iosuiviewcontrolleruikituicontainerview

Get Parent ViewController from within embedded child UIViewController


How do I get a reference to the parent UIViewController from within a controller which is embedded in it using a Container View?

I want to access the Parent from within the Child.


Solution

  • When you add view controller in container view it is added as child view controller

    You can access child it like following way

      if let yourVC:YourViewController = self.childViewControllers.first(where: {$0 is yourVC:YourViewController}) as? YourViewController {
            // Here you got it 
    
        }
    

    You can access Parent with parent property of viewController

      if let parent = self.navigationController?.parent as? ParentControllerType {
    
         // Do what you want with the parent.
    
       } 
    

    see this https://developer.apple.com/documentation/uikit/uiviewcontroller/1621362-parent

    Hope it is helpful