Adding a new Viewcontroller view as a subtask

I am trying to do the following and could not add a new view to the viewcontrollers. Is this the only way to present a view controller? Can't add a view from other views? Viewboard viewcontrollers?

  //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)
+4
source share
1 answer

You also need to add CustomViewControllerboth ChildViewControllerto the 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)
+8
source

Source: https://habr.com/ru/post/1669144/


All Articles