Swift 3 - How to instantiate a View Controller?

Asked

Viewed 430 times

0

I need to work with a method with attributes that are in another Viewcontroller but I can’t do it.
What I’m trying to do:

let notasViewController: NotasViewController()

And also:

let notasViewController: NotasViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NotasViewController") as! NotasViewController

Always returns EXC_BAD_ACESS or an error saying that my Storyboard does not contain this View Controller
Any help? Thank you!

2 answers

2


It will be basically 2 steps to be done in Storyboard:

  1. In his Main.storyboard, select the desired Viewcontroller and modify the class of the same to Notasviewcontroller.
  2. Modify the Storyboard ID field, with the name of the identifier you will use in the code, in the case of your code, you are using: "Notasviewcontroller"

The settings would look like this:

inserir a descrição da imagem aqui

The "Use Storyboard ID" box is not required to be checked, it serves if you want to leave the "Restoration ID" with the same identifier ID on Storyboard.

Once done, go to the View Controller class that you want to have an instance of the class NotasViewController and use the same code you used:

let notasViewController: NotasViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NotasViewController") as! NotasViewController

Then you will have access to class methods NotasViewController through the constant notasViewController.

-1

You can do this to create a new instance of Viewcontroller:

let notasViewController = NotasViewController()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.