Linking Separate Storyboards Together - Swift 2.0, Xcode 7 and Interface Builder - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 1. Swift 2.0, Xcode 7 and Interface Builder

1.7 Linking Separate Storyboards Together

Problem

You have a messy storyboard, so you would like to place some view controllers in their own storyboard and still be able to cross-reference them in your other storyboards.

Solution

Use IB’s new “Refactor to Storyboard” feature under the Editor menu.

Discussion

I remember working on a project where we had a really messy storyboard and we had to separate the view controllers. What we ended up doing was putting the controllers on separate storyboards manually, after which we had to write code to link our buttons and other actions to the view controllers, instantiate them manually, and then show them. Well, none of that anymore. Apple has taken care of that for us!

As an exercise, create a single view controller project in Xcode and then open your main storyboard. Then choose the Editor menu, then Embed In, and then Navigation Controller. Now your view controller has a navigation controller. Place a button on your view controller and then place another view controller on your storyboard. Select the button on the first view controller, hold down the Control button on your keyboard, drag the line over to the second view controller, and then choose the Show option. This will ensure that when the user taps on your button, the system will push the second view controller onto the screen. Figure 1-2 shows...

Figure 1-2. We need to create a show segue ensuring that pressing our button will show the second view controller

Now select your second view controller and then, from the Editor menu, choose the “Refactor to Storyboard” item. In the dialog, enter “Second.storyboard” as the file name and save. That’s really it. Now run your app and see the results if you want.

If you prefer to do some of this stuff manually instead of embeding things like this, you can always drag the new item called Storyboard Reference from the Object Library onto your storyboard and set up the name of the storyboard manually. Xcode will give you a drop-down box so that you don’t have to write the name of the storyboard all by yourself. You will also be able to specify the identifier the first view controller inside this new storyboard that has to be initialized by this segue. You of course have to set this ID up for your view controller in advance.

See Also