0

I have to add second view controller's view on UIWindow of the first view controller using addChildViewController. but I'm getting issue when I'm trying to do that. My query is, it is possible to add that another view controller's view on UIWindow?

    secondVC = (self.storyboard?.instantiateViewController(withIdentifier: "secondVC"))!
    self.addChildViewController(secondVC)
    self.didMove(toParentViewController: self)
    draw.view.frame = CGRect(x:0, y:0, 320, 568)

    let window = UIApplication.shared.keyWindow
    window?.addSubview(secondVC.view)
ssowri1
  • 1,299
  • 2
  • 14
  • 31

1 Answers1

1

Well, maybe you should instantiate the root VC and then add the second VC into the first VC of your app. For example you could write something like that:

//init the storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
//init the firstVC
let navigation = storyboard.instantiateInitialViewController() as! UINavigationController
let firstVC = navigation.viewControllers[0]
//init the second VC
let secondVC = (self.storyboard?.instantiateViewController(withIdentifier: "secondVC"))!
//add child VC
firstVC.addChildViewController(secondVC)
secondVC.view.frame = firstVC.view.bounds
self.view.addSubview(controller.view)
secondVC.didMove(toParentViewController: self)

This is because the main window has the root VC associated. The keywindow has the initial view controller from the main Storyboard.

Alfredo Luco G
  • 876
  • 7
  • 18
  • 1
    Well, Do u mean that you embed a navigation controller on your root vc? – Alfredo Luco G Sep 27 '17 at 14:12
  • Yeah. I linked the navigation controller to first viewcontroller – ssowri1 Sep 28 '17 at 06:16
  • Ok, In that case you need to put a storyboard ID on your navigation controller and then instantiate your firstVC as a navigation vc, then you can get the viewControllers's property of navigation controller and get the firstView controller to add your child VC. I will edit the code. – Alfredo Luco G Sep 28 '17 at 19:07