Learn to seamlessly pass data between Table View Controller and Detail View Controller using segues in iOS development. Gain a deep understanding of creating mutable arrays and connecting band detail outlets in code.
Key Insights
- The tutorial covers creating mutable arrays and connecting band detail outlets in code in iOS development.
- Students learn to pass data between the Table View Controller and the Detail View Controller using a segue, added in an earlier exercise.
- The mutable arrays are created for band titles using 'let' for immutable objects and 'var' for mutable objects.
- Mutable objects, unlike immutable objects, can be updated after creation.
- The band detail outlets are connected with the code to allow them to be displayed on the view. This involves creating outlets for each element on the page.
- The tutorial also guides users through the process of viewing and testing the application in a simulator, which helps visualize the results of the coding exercises.
Dive into this comprehensive tutorial to learn iOS Development, covering topics like creating a mutable array and connecting band detail outlets in code.
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:
Creating a Mutable Array, Connecting Band Detail Outlets in Code
Exercise Overview
In this exercise, you’ll learn how to pass data between the Table View Controller and the Detail View Controller via the segue we added in an earlier exercise.
Getting Started
-
If you completed the previous exercise you can skip the following sidebar. We recommend you finish the previous exercises (1B–2A) 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–2A)
- 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 More Segues folder.
- Rename the folder to Jive Factory.
- Open Jive Factory > Jive Factory.xcodeproj.
Creating a Mutable Array (Let Vs. Var)
We have the objects for our bands created, and now we need to be able to pass along the correct object depending on the row the user clicks. If you remember from a previous exercise, we used an array to hold the Titles for the different bands, then pulled the correct band title depending on what the user clicked. We need to do a similar thing for these objects. The arrays we created for bandTitles etc. are prefixed with let. When you use let you are creating a constant or immutable object. However, when you use var you are creating a mutable object. Only mutable objects are allowed to be updated after creation.
- In the Project navigator, click on BandsTableViewController.swift.
-
Below the bandImageNames property, add the following bold code:
let bandImageNames = ["thumb-nicole-atkins", "thumb-ambulance-ltd", "thumb-sleepies", "thumb-black-angels"] var bandDetails = [BandDetail]() override func viewDidLoad() {
Notice that we use var to create a mutable object. We set the name of our object to bandDetails and we set the object to an array that contains the type BandDetail. In Swift an array must contain only one data type (in this case we set it to our custom object of BandDetail).
-
Now that we have the bandDetails mutable array to work with, let’s add the BandDetail objects to it. Find the code for the last band object we created (blackAngelsDetails) and add the following bold code after it:
blackAngelsDetails.showDetails = "Over 21—$15" bandDetails.append(nicoleAtkinsBandDetail) bandDetails.append(ambulanceLtdDetails) bandDetails.append(sleepiesDetails) bandDetails.append(blackAngelsDetails) }
Because the structure of our app is getting more complex, below is a chart that explains how information will pass through it. Some parts we’ve already created, and the rest we’ll create in the remainder of this exercise.
- In the Project navigator, click on BandsDetailViewController.swift.
-
At the top, create a property called currentBandDetail by adding the bold code shown below:
class BandsDetailViewController: UIViewController { var currentBandDetail:BandDetail? override func viewDidLoad() {
- Go to BandsTableViewController.swift.
-
Near the bottom, add the bold code inside the prepare (for segue) method:
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 bandsDetailViewController.currentBandDetail = bandDetails[indexPath.row] } } }
Let’s break this code down for you. We are setting the currentBandDetail object in the bandsDetailViewController equal to the object in the bandDetails mutable array at the specified indexPath.row. It figures out the correct indexPath.row based on the row that is clicked. If you remember, we set this in the first line of the code in the if statement. Awesome! Next we’ll get all the labels in the Detail View Controller displaying the correct info from the object that’s passed.
Connecting Band Detail Outlets in Code
Let’s connect each of our Band Detail elements with the code so that they will be displayed on the View.
- In the Project navigator click on Main.storyboard.
- If the Document Outline is open, click Hide Document Outline
.
- Click the top bar of the Bands Detail View Controller so that it is selected in the Editor area.
- At the top right of the window, click the Assistant editor button
because we want to see the storyboard next to BandsDetailViewController.swift.
- If BandsDetailViewController.swift isn’t showing on the right side, choose it from the menu at the top of the code.
- You should now have the storyboard showing on the left and BandsDetailViewController.swift on the right. We are going to create outlets for each of the elements on this page.
- In the storyboard, make sure you can see the Bands Detail View Controller with all the placeholder labels (Name of Band, Type of music, etc.). You’ll probably have to scroll over to the right side of the storyboard.
-
As shown below, hold Control or the Right mouse button and drag the Name of Band label to the BandsDetailViewController.swift file beneath the BandDetail property line.
-
In the menu that pops up, set the following:
Name: bandNameLabel Storage: Weak - Click Connect (or hit Return).
-
Repeat this same process for the rest of the labels and the image, adding each just below the previous one. In the pop up menu, set Storage to Weak and Name to the following values:
Type of music: bandTypeLabel Venue: venueLabel Date: showDateLabel Time: showTimeLabel Age / price: showDetailsLabel Description: bandDescriptionLabel Band image: bandImage -
When finished, the code you added should look like this:
var currentBandDetail:BandDetail? @IBOutlet weak var bandNameLabel: UILabel! @IBOutlet weak var bandTypeLabel: UILabel! @IBOutlet weak var venueLabel: UILabel! @IBOutlet weak var showDateLabel: UILabel! @IBOutlet weak var showTimeLabel: UILabel! @IBOutlet weak var showDetailsLabel: UILabel! @IBOutlet weak var bandDescriptionLabel: UILabel! @IBOutlet weak var bandImage: UIImageView! override func viewDidLoad() {
- At the top right of the window, switch back to the Standard editor
.
- In the Project navigator, select BandsDetailViewController.swift.
-
Find the viewDidLoad method and add the following bold code:
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. bandNameLabel.text = currentBandDetail?.bandName bandTypeLabel.text = currentBandDetail?.bandType venueLabel.text = currentBandDetail?.venue showDateLabel.text = currentBandDetail?.nextShowDate showTimeLabel.text = currentBandDetail?.nextShowTime showDetailsLabel.text = currentBandDetail?.showDetails bandDescriptionLabel.text = currentBandDetail?.bandDescription bandImage.image = UIImage(named: currentBandDetail!.fullImageName!) }
- Click the Run button.
-
When the Simulator loads, click on Nicole Atkins.
The detail view will load. It should now be populated with the correct info!
- Click the Bands button at the top left to go back to the list of bands.
-
Click on another band to go to the detail view and see it is populated with the correct info for that band as well.
Notice the description at the bottom gets cut off. There should be two lines of description. Let’s fix that.
- Switch back to Xcode.
- Click the Stop button.
-
In the Project navigator, click on Main.storyboard to view it.
(If you don’t see it, click the Project navigator tab
.)
- Click on the Description label to select it on the view.
-
In the Attributes inspector
, set Lines to 2 and hit Return.
NOTE: This specifies the line limit. If the text is longer than the limit, it will be truncated and an ellipse (…) will be added at the end of the text. Setting the limit to 0 would give you an unlimited number of lines.
- Click the Run button.
- Click on any band (except for Nicole Atkins, which only has one line of content) to switch to the detail view. Notice the full 2-line description is now listed.
- Switch back to Xcode.
- Click the Stop button.
Save the project and leave it open so we can continue to work on it in the next exercise.