5

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)

1 Answer 1

10

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)
Sign up to request clarification or add additional context in comments.

7 Comments

you missed the another one line
or use vc.willMove(toParentViewController: self)
@Anbu.Karthik Edited for that
thank you! I have tried for adding some other views vc.customView to self.view but failed. Is this possible to add part of vc with defined frame into self.view like self.view.addsubview(vc.customview) : vc from storyboard
@GobiM I haven't try something like that, have you try by adding it, vc.customview is not load yet so may be it will give you nil, You can check it by simply trying once.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.