Now let’s make a XIB-based view controller we can play with. As with the storyboard version, we’ll want it to have two things:
Let’s define a new view controller for the XIB-based version. Select the LoadViewControllers group in the Project Navigator. Create a new file, selecting Cocoa Touch Class. Name it XIBBasedViewController and make it a subclass of UIViewController. This time, select the check box labeled “Also create XIB file.” Your selections should look like this:
In the Save dialog, double-check that the app target is selected, not the test target, then press Create. This will add XIBBasedViewController.swift and XIBBasedViewController.xib to the project.
Now define an outlet—a label will do for our experiment. In the Swift file, use the following code:
| class XIBBasedViewController: UIViewController { |
| @IBOutlet var label: UILabel! |
| } |
Next, let’s add a label so we can connect it to the view controller’s outlet. Open XIBBasedViewController.xib and select View ▶ Libraries ▶ Show Library from the Xcode menu, or press Shift-⌘-L. Drag a label onto the view in the main editor area. For this experiment, don’t worry about positioning the label or setting any Auto Layout constraints.
Then connect the outlet to this new label. (One way to do this is to show XIBBasedViewController.swift in the Assistant Editor. Click in the open circle next to @IBOutlet and drag it to the label on the view to establish the connection.)