Discover how to create a segue in iOS development to pass information between views, specifically for creating a class for the Detail View Controller. Learn how to utilize segues to transition users between views and create an object to hold all the relevant information for each view.
Key Insights
- The tutorial covers how to create a segue in iOS development, which enables passing information between views.
- A class for the Detail View Controller is created to allow for extra functionality programming.
- A 'segue' in iOS development is an object that performs visual transitions between view controllers. Prior to this transition, a 'prepare(for segue: UIStoryboardSegue, sender: Any?)' method is called in the source view controller. This is where data may be passed to the destination view controller.
- An object is created to hold all the information for a single band and is passed between the Table View and Detail View controllers.
- The 'BandDetail.swift' class is created with nine properties including bandName, bandType, bandDescription, fullImageName, thumbImageName, nextShowDate, nextShowTime, venue, and showDetails.
- Code is added to the 'super.viewDidLoad()' method in 'BandsTableViewController.swift' to create objects for each of the four bands and set their properties accordingly.
Master the art of iOS development by learning how to create a segue to pass information between views, create a class for the Detail View Controller, and understand the nuances of segues in this comprehensive tutorial.
This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics Covered in This IOS Development Tutorial:
Segues, Creating a Band Detail Object
Exercise Preview
Exercise Overview
In this exercise, you’ll learn how to create a segue to pass information between views.
Getting Started
-
If you completed the previous exercise you can skip the following sidebar. We recommend you finish the previous exercises (1B–1E) before starting this one.
If you completed the previous exercise, Jive Factory.xcodeproj should still be open. If you closed it, re-open it (from yourname-iOS Dev Level 2 Class > Jive Factory).
If You Did Not Complete the Previous Exercises (1B–1E)
- Close any files you may have open and switch to the Desktop.
- Navigate to Class Files > yourname-iOS Dev Level 2 Class.
- Duplicate the Jive Factory Ready for Segues folder.
- Rename the folder to Jive Factory.
- Open Jive Factory > Jive Factory.xcodeproj.
Creating a Class
As we did in a previous exercise for the Table View Controller, we need to create a class for the Detail View Controller so we can program extra functionality for it.
- In the Project navigator, select BandsTableViewController.swift. (We want the file to be added after this file, that’s why we had you select it.)
- Go to File > New > File (or hit Cmd–N).
- Under iOS and Source, double–click on the Cocoa Touch Class template.
- From the Subclass of menu, choose UIViewController (or start typing it and let Xcode autocomplete it for you).
-
For the name of the Class, add BandsDetail at the start, so the Class ends up being BandsDetailViewController. (Notice that is Bands plural, not Band!)
NOTE: UIViewController is the type of object we are currently using on the storyboard. By making our class a subclass of the UIViewController, it will have all the functionality it currently has, plus any additional functionality we add in the code to this new BandsDetailViewController class.
- Click Next.
- You should already be in the Jive Factory folder, so click Create.
- Notice a BandsDetailViewController.swift file has been added in the Project navigator. Now we need to link it to the view controller in the storyboard.
- In the Project navigator click on Main.
- In the Document Outline, select View Controller (inside View Controller Scene). It will become outlined in blue to indicate it’s selected.
- In the Utilities area on the right, click on the Identity inspector tab
.
- Next to Class, type B and it should autocomplete to BandsDetailViewController.
Hit Return to apply it. Now it’s connected to our new class.
What is a Segue?
In a previous exercise, we added a segue that transitions users from the Table View to the Detail View when they click on a band row. Let’s read up a bit about segues to see how we can use them to display the appropriate info in our detail view.
- Go to Help > Developer Documentation.
-
Into the search field, type UIStoryboardSegue and click on the first result (which should be for UIStoryboardSegue).
One basic thing to note is that segue (pronounced seg-way) objects perform the visual transition between view controllers. Before this transition occurs, a prepare(for segue: UIStoryboardSegue, sender: Any?) method is called in the source view controller. It is in this method that we may choose to pass some data to the destination view controller.
- The prepare method is a commonly-used method, so Xcode created it for you when you created the table view controller. Before going back to the code, close the Documentation window.
-
In the Project navigator, click on BandsTableViewController.swift.
NOTE: The code we are looking for is only in this file. Take a moment to make sure you’re in the 100+ line Table View file, NOT the new Detail View file!
-
Scroll to the bottom of the document and find the following code:
/* // MARK:—Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */
Delete the
/*
above the // MARK:—Navigation line so that we can uncomment the code and use it.-
Delete the
*/
below the closing brace } of the method.Now we will replace the comments inside of the method with some code. To save you time, we already typed it up in a text file for you.
- Go to File > Open.
- Navigate to the Desktop > Class Files > yourname-iOS Dev Level 2 Class > Code Snippets folder and open prepareForSegue.txt.
- Press Cmd–A to select all the code.
- Press Cmd–C to copy it.
- Close the file.
- Delete the two lines of comments inside the prepare method.
-
In its place, paste the code you copied:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showDetail") { if let indexPath = self.tableView.indexPathForSelectedRow { let bandsDetailViewController:BandsDetailViewController = segue.destination as! BandsDetailViewController } } }
-
Let’s break this code down. The prepare method was conveniently written for us by Xcode. Inside this method we wrote an if statement that checks to see which segue was triggered. If that segue’s identifier is equal to showDetail then the code inside the if statement is executed. showDetail is the name we’ll assign to our segue (which we’ll do a bit later).
Inside the first if statement is another if statement which asks the current table view for the index path of the row that was selected. The index path is how we know which row was tapped. This will help us set the correct info for each band later.
The first line of code inside the second if statement sets the view controller we are transitioning to, which is BandsDetailViewController.
In order for the code we just added to execute when someone clicks on one of the rows, we need to set the identifier on the segue in the storyboard to showDetail. The first if statement we just added refers to showDetail, which is the name we’ll give to our segue. Let’s set that now.
- In the Project navigator, click Main.storyboard.
-
As shown below, in the Editor, click on the segue between the Table View and Detail View Controllers to select it.
- In the Utilities area on the right, click the Attributes inspector tab
.
-
Next to Identifier, type showDetail and hit Return.
The code inside the if statement in the prepare method will now execute when this segue happens. Next we can work on passing along the necessary information.
Creating a Band Detail Object
We have quite a bit of information we need to pass along in the segue. The best way to do this is to create an object that will hold all the info for a single band and pass that between the Table View and Detail View controllers.
- In the Project navigator, select BandsDetailViewController.swift. (We want the file to be added after this file, that’s why we had you select it.)
- Go to File > New > File (or hit Cmd–N).
- Double–click Cocoa Touch Class to choose it.
- From the Subclass of menu, choose NSObject (or start typing it and let Xcode autocomplete it for you).
- Next to Class, type BandDetail (that is singular Band, not plural!).
- Click Next.
- You should already be in the Jive Factory folder, so click Create.
- Notice that BandDetail.swift has been added in the Project navigator.
- Click on BandDetail.swift to open it if it isn’t already.
-
Let’s start by adding our properties. After the opening curly brace { add the following bold code to add a property for the band’s name:
class BandDetail: NSObject { var bandName: String? }
- We have some more properties to add. To speed things up, let’s copy the property line we just added. Select the var line you just added.
- Hit Cmd–C to copy it.
- Hit Cmd–V to paste it below the original eight times (so we have a total of nine property lines).
-
Edit the code as shown below:
class BandDetail: NSObject { var bandName:String? var bandType:String? var bandDescription:String? var fullImageName:String? var thumbImageName:String? var nextShowDate:String? var nextShowTime:String? var venue:String? var showDetails:String? }
- Do a File > Save.
- To save you some time, we’ve already written the code that will create the objects for each of the four bands. Go to File > Open.
- Navigate to the Desktop > Class Files > yourname-iOS Dev Level 2 Class > Code Snippets folder and open band-detail-objects.txt.
- Press Cmd–A to select all the code.
- Press Cmd–C to copy it.
- Close the file.
- Go to BandsTableViewController.swift.
- Select and delete the commented out line in the super.viewDidLoad() method (near the top of the file).
-
As shown below, paste the code where the commented code used to be:
override func viewDidLoad() { super.viewDidLoad() let nicoleAtkinsBandDetail = BandDetail() nicoleAtkinsBandDetail.bandName = "Nicole Atkins" nicoleAtkinsBandDetail.bandType = "Rock" nicoleAtkinsBandDetail.bandDescription = "Nicole will knock your socks off."
Code Omitted To Save Space
blackAngelsDetails.venue = "Cake Shop" blackAngelsDetails.showDetails = "Over 21—$15" }
TIP: If the code you just pasted is not indented correctly, select those lines of code, and CTRL–click or Right–click on the code. In the menu that appears, select Structure > Shift Right. That should fix it.
- Scroll through the code you just pasted. Note that each block of code creates a new object and sets its properties. The first line creates an object of the type BandDetail by allocating memory to it and initializing it. The rest of the code sets the different properties we created when we built the BandDetail class to the correct details for the band.
- Do a File > Save.
There is still more to do, but that’s enough for this exercise! Leave the project open. We’ll continue to work on it in the next exercise.