Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new Viewcontroller's view as subview

I am trying with the following and failed to add new viewcontrollers view. Is it only way to present view controller ? Cant we add view from other storyboard viewcontrollers view?

  //Working
    let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customView") as! CustomViewController

    self.present( viewcontroller , animated: true, completion: nil)

    //Not working
    let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customView") as! CustomViewController
    vc.view.frame = self.view.frame
    self.view.addSubview(vc.view)
like image 754
Gobi M Avatar asked Feb 08 '17 10:02

Gobi M


1 Answers

You need to also add CustomViewController as ChildViewController in your current Controller.

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "customView") as! CustomViewController
vc.view.frame = self.view.bounds
self.addChildViewController(vc)
self.view.addSubview(vc.view)
vc.didMove(toParentViewController: self) //OR  vc.willMove(toParentViewController: self)
like image 179
Nirav D Avatar answered Oct 16 '22 10:10

Nirav D