Academy for iOS App Development

Exercise 2:
Friends

In this exercise, the home screen of our app will consist of a list of ten friends. When you select one of them from the table, we will segue to a second screen where we can see information about the selected friend.

Getting Started

The user interface of your project should look like the following. (The image of the second screen shows what it would look like if the user had selected Bruce Wayne on the first screen.)

Picture of Storyboard
Figure 1. The two screens in your project.


Part 1

The two screens in the user interface should look like Figure 1.

  1. Create a new project.
  2. Drag a Table View from the library to the main View Controller and stretch it to fill the safe area of the screen.
  3. With the Table View selected, go to the Attributes Inspector. Set the value of the field Prototype Cells equal to 1.
  4. Select the Table View Cell. Set the Identifier to TextCell, and change the Style to “Subtitle”.
  5. Add an outlet for the Table View called tableView to the ViewController class.
  6. Add “, UITableViewDataSource, UITableViewDelegate” to the ViewController class after UIViewController. (Don't forget the comma at the beginning!) An error will show, indicating we haven’t met the requirements for the UITableViewDataSource yet. Ignore it for now.
  7. For the data source for your table, create three global arrays lastNames, firstNames, and friendData at the top of the file, between the "import UIKit" statement and the class definition for ViewController. These arrays will contain the names of your friends, along with some personal information about each one. Here's an example:
    public let lastNames = [
        "Kent", "Wayne", "Prince", "Allen", "Queen",
        "Curry", "Jordan", "Stone", "Jones", "Drake"
    ]
    
    public let firstNames = [
        "Clark", "Bruce", "Diana", "Barry", "Oliver",
        "Arthur", "Hal", "Victor", "John", "Dinah"
    ]
    
    public let friendData = [
        "Superman \n   Home: Metropolis \n   Nemesis: Lex Luthor",
        "Batman \n   Home: Gotham City \n   Nemesis: Joker",
        "Wonder Woman \n   Home: Themyscira \n   Nemesis: Cheetah",
        "Flash \n   Home: Central City \n   Nemesis: Professor Zoom",
        "Green Arrow \n   Home: Star City \n   Nemesis: Merlyn",
        "Aquaman \n   Home: Atlantis \n   Nemesis: Black Manta",
        "Green Lantern \n   Home: Coast City \n   Nemesis: Sinestro",
        "Cyborg \n   Home: Detroit \n   Nemesis: Slade",
        "Martian Manhunter \n   Home: Mars \n   Nemesis: Darkseid",
        "Black Canary \n   Home: Gotham City \n   Nemesis: Vertigo"
    ]
    
    where "\n" is used to insert a line break. You should use your own friends and data for the exercise.
  8. Add code into ViewDidLoad to identify the delegate and the data source:
        tableView.delegate = self
        tableView.dataSource = self
    
  9. Add the following functions to the ViewController class right after the ViewDidLoad function:
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection
                             section: Int) -> Int {
            return lastNames.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TextCell", for: indexPath as IndexPath)
            let row = indexPath.row
            cell.textLabel?.text = lastNames[row]
            cell.detailTextLabel?.text = firstNames[row]
            
            return cell
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let row = indexPath.row
            print(lastNames[row])
        }
    
    Now the error you saw earlier should be gone since we’ve implemented everything we need for the data source.

Run the simulator now to see if you get any errors. If you did everything correctly, you should see a screen that looks like the left screen in Figure 1.

Part 2

  1. Drag a View Controller from the library into the storyboard. Add a label and a Text View (which is like a multi-line Text Field) and place them roughly where they appear in the right screen in Figure 1. Call them “Name Label” and “Friend Data”.
  2. Add a segue by ctrl-dragging from the Text Cell to the new VC. In the popup that appears, choose “Show”. Select the segue in the storyboard, and use the Inspector to change the identifier to the string “FriendSegueIdentifier”.
  3. Now we're going to create a custom class in a separate file to contain the code for the new VC. Go to the Xcode menu at the top of your screen and select File -> New -> File. On the iOS source tab, choose "Cocoa Touch Class". In the popup that appears, make it a subclass of UIViewController and name it “FriendViewController”.
  4. Select the new VC in the storyboard. In the Inspector, change the class to FriendViewController.
  5. Create outlets for the label and Text View. Name the variables nameLabel and textView.
  6. Select the table cell. In the Attribute Inspector, change the Accessory value to "Disclosure Indicator". (This will add a ">" symbol to the right side of each of the table rows as a visual hint to the user that clicking the row will take you to another screen.)
  7. Add the following code to the FriendViewController class right after the outlets:
     
        var lastName:String = ""
        var firstName:String = ""
    
  8. Add the following function to the FriendViewController class right after the ViewDidLoad function:
     
        override func viewWillAppear(_ animated: Bool) {
            nameLabel.text = firstName + " " + lastName
            let nameIndex = lastNames.firstIndex(of: lastName)
            textView.text = friendData[nameIndex!]
        }
    
  9. Add code to class ViewController for handling the segue to the next screen:
     
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "FriendSegueIdentifier",
               let destination = segue.destination as? FriendViewController,
               let nameIndex = tableView.indexPathForSelectedRow?.row
            {
                destination.lastName = lastNames[nameIndex]
                destination.firstName = firstNames[nameIndex]
            }
        }
    

Run the simulator now to see if you get any errors. If you did everything correctly, you should be able to select one of your friends' names and get to the Friend VC. However, there's no way to get back to the main VC yet. We need to add a Navigation Controller.

In the storyboard, select the main VC. Then go to the Xcode menu at the top of the screen and select Editor -> Embed In… -> Navigation Controller. Build and run. This time, there should be a "Back" button on the second VC that enables you to get back to the first one and choose another friend's name.

Additional Exercises