ssowri1
ssowri1

Reputation: 1317

Swift 3 - addChildViewController on UIWindow of another view controller

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)

Upvotes: 0

Views: 2985

Answers (1)

Alfredo Luco G
Alfredo Luco G

Reputation: 974

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.

Upvotes: 1

Related Questions