Let’s make a storyboard-based view controller we can play with. We’ll want it to have some of the basics:
The default storyboard already contains a view controller, but let’s add a new one. Storyboards usually contain more than one view controller, so we need to be able to access any of them, not just the initial one.
First, let’s define a new view controller for the storyboard-based version. Select the LoadViewControllers group. Create a new file, selecting Cocoa Touch Class. Name it StoryboardBasedViewController and make it a subclass of UIViewController, like this:
In the Save dialog, double-check that the app target is selected, not the test target.
Now let’s define an outlet—a simple label will do. Change the code as follows:
| class StoryboardBasedViewController: UIViewController { |
| @IBOutlet var label: UILabel! |
| } |
Next, let’s add this view controller to the storyboard. Open Main.storyboard and select View ▶ Libraries ▶ Show Library from the Xcode menu, or press Shift-⌘-L. This will bring up the Object Library. Find “View Controller” and double-click it to add a new view controller to the storyboard. (If you can’t see the View Controller item, make sure you’ve selected Main.storyboard.)
This will create a generic view controller, which we need to change to our specific type. Select the second “View Controller Scene,” which is the one we just added, as shown here:
In the Xcode menu, select View ▶ Inspectors ▶ Show Identity Inspector or press ⌥-⌘-4. In the Identity Inspector on the right, the Custom Class section will show that the class of the selected view controller is UIViewController. (If it shows ViewController, that’s the wrong one.) It will appear as follows:
Click the down arrow for Class to reveal the pull-down menu, and select StoryboardBasedViewController.
Let’s add a label so we can connect it to the view controller’s outlet. Open the Object Library again and drag a label onto the view controller in the main editor area. For this experiment, don’t worry about positioning the label or setting any Auto Layout constraints.
Finally, connect the outlet to this new label. (One way to do this is to open StoryboardBasedViewController.swift in the Assistant Editor. Click in the open circle next to @IBOutlet and drag it to the label on the storyboard to establish the connection.)