Your View Controllers are created by the Storyboard automatically depending their defined relationships in Interface Builder.
Sometimes however we need to create and transition to View Controllers we’ve defined in code. For example, if you want to transition to a view as part of displaying a search result.
We can do this by creating a new UIStoryboard object and then asking it to create a View Controller defined in it. For this to work you need to give your View Controller a unique identifier using the Identity Inspector (under Identity, set a Storyboard ID).
This example assumes we have a Storyboard file called MainStoryboard.storyboard in which there’s a View Controller called DetailView. Here’s how we create it and push it onto a stack of Navigation Controllers:
If the App Delegate has something that your top view controller needs then you simply pass it the required object via a property set on the top view controller. This is easy when your top view controller is also the root view controller.
However, when you embed your top view controller in a Navigation Controller, and perhaps that one is also embedded in a Tab Bar Controller, then this array isn’t quite so easy to figure out (and I must admit that I always forget how to do this when a new challenge arises).
So here’s how this works. In this example, the thing that’s displayed is called MyViewController, which is embedded in a Navigation Controller. I’m passing it the App Delegate’s self.managedObjectContext which is defined as a property on MyViewController.
Here’s an example. MyNavController is the class for the Navigation Controller. This snipped is called from any View Controller in sequence and assumes we have an integer myNumber which is increased by one:
If you have two view controller classes you probably want to exchange data between them. Thanks to two methods we can do that, provided one view controller is presented via a modal segue. Here’s how it works step by step.
Imagine you had two labels on each View Controller. We’ll call them myLabel1 and myLabel2 (1is on ViewController, 2 on MyViewController). Both View Controllers need to be connected as described previously via a segue. You can access properties on ViewController from MyViewController like so: