Tutorial – Navigation between View Controllers
In this tutorial we will look at navigation in Swift, using segue’s and the navigation controller to navigate between different view controllers.
To start off with we have created a new blank single view application and changed the Main.storyboard as follows:
- Add two new view controllers to the right of the default view controller
- Add two buttons to the default controller – Page 1 and Page 2
- Add a label to identify the new view controllers – 1 & 2
Now we are going to create the segue to navigate to page 1 & 2. To make a segue click on button 1, hold down the control key and drag the line and drop it on the view controller with number 1. You will see the following menu:
Select “Show” from the action segue, and repeat the same steps for Page 2. Now run the App & test the buttons – you will be able to click on the buttons to navigate through our app. But wait a minute, theres a problem?!?! Once you have navigated to another view you cannot go back. To resolve this you can either
- Make buttons on the 1 & 2 view controllers to go back to the first one (This makes the storyboard a mess)
- Or even better use the Navigation Controller to manage it all for you automatically!
So lets look at how to use this magical Navigation controller. On your storyboard in the Object library simply search for the Navigation Controller, and drag this onto your storyboard, to the left of the default view controller with the Page 1 & Page 2 buttons. Now also drag the right arrow from the default view controller so it set’s to the left of our new navigation controller. Your storyboard should look something like the following:
Now select the navigation controller you placed, hold down the control key and the line to our default view controller (The one with the page 1 & page 2 buttons), drop it on here and from the menu select “root view controller”. Run your app now & try the buttons out! You will now notice there is a navigation bar up the top and you can choose the Back button to go back. This makes it easy to navigate your app without any additional coding. If you wish to name the titles of your navigation bar up the top simply drag the Navigation Item from the object library to your navigation bar and you can set the title up the top.