Swift 3 - 另一个视图控制器的UIWindow上的addChildViewController

时间:2017-09-27 13:20:37

标签: ios swift3 uiwindow childviewcontroller childviews

我必须使用addChildViewController在第一个视图控制器的UIWindow上添加第二个视图控制器的视图。但是当我尝试这样做时,我会遇到问题。我的查询是,可以在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)

1 个答案:

答案 0 :(得分:1)

好吧,也许您应该实例化根VC,然后将第二个VC添加到您应用的第一个VC中。例如,你可以这样写:

//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)

这是因为主窗口具有关联的根VC。 keywindow具有主Storyboard中的初始视图控制器。