Add child view controller to current view controller

后端 未结 5 1396
梦毁少年i
梦毁少年i 2020-11-28 11:10

I am trying to add a child view controller in code, to the current view controller from storyboard by using the next code:

UIStoryboard *storyboard = [UIStor         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 11:49

    Solution in Swift (Swift 4 at the time of this writing):

    //load the view controller and add as child
    storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    loginVC = storyboard.instantiateViewController(withIdentifier: "LOGIN")
    addChildViewController(loginVC)
    
    //make sure that the child view controller's view is the right size
    loginVC.view.frame = contentView.bounds
    contentView.addSubview(loginVC.view)
    
    //you must call this at the end per Apple's documentation
    loginVC.didMove(toParentViewController: self)
    

    Notes:

    • Storyboard name is "Main".
    • View controller identifier in the storyboard is named "LOGIN".
    • This uses a storyboard to create load the view controller, but the same can be done programmatically. Just make sure the view is loaded into memory before you try and access the view's frame or you will get a crash (do something like present the view controller modally).

提交回复
热议问题