TableView … it is everywhere – A Swift Way to Get Into iOS Development #3

Today, we look into TableView. They are a heavily used UI element in nearly every app today. Snapchat uses them for their chat overview. Instagram uses them to show you your feed. They are basically everywhere.

New Project? Check!

Like I said last time I assume you know how to create a new project and set it up correctly. If you suddenly forgot, no worries, I got your back. Here’s the link to the first tutorial.
How To Setup a New Project

So today we are going to implement a TableView with one of the default styles Apple provides. The project is named TableViewIntroduction, organization, devices, language etc. are the same as always.

table-views-project-window
Set up your project and let’s get into TableViews.

The Seven Highest Mountains

Our app will need to serve a certain purpose. In this case it will display the Seven Summits. The highest mountain of each continent, from the tallest to the “shortest” with a name and the altitude.

So let’s switch to our Main.storyboard file. Here you can see that we have our standard UI. A blank ViewController. This time we don’t need a ViewController so you can select it and delete the whole ViewController. We need a blank Storyboard.

table-view-interface-builder
Today we won’t need a ViewController, not directly. We use a subclass called TableViewController

After you’ve done that you go to your Object Library and search for/scroll to TableViewController. And drag it onto your empty Storyboard.

table-view-controller
A TableViewController is specifically made to handle everything concerning a TableView.

Showing the Storyboard where to start

Because we deleted our automatically generated ViewController we need to tell the Storyboard which ViewController is our initial one. You can easily do that by selecting the whole ViewController, by clicking on the bar on top of it. Now the Utilities section, under the Attributes Inspector tab, shows the check box for Is Initial View Controller. Make sure to check that and you are good to go.

table-views-initial-view-controller
A Storyboard needs an starting point. Otherwise it won’t display anything.

You should now have an Interface Builder that looks roughly like this.

table-view-initial-view-controller
Now that we have replaced the first ViewController with a TableViewController we can begin to change some of the settings.

But … there’s only one cell. We need more.

By clicking on the white rectangle, below the Prototype Cells label, you can select one of the cells. This cell is, like the name implies, a blueprint for all the cells in the TableView.  Your Attributes Inspector shows some of the cell’s settings. You want to choose a predefined style, the prototype cell should then change its design. In our case Right Detail and you want to set the Identifier to mountainCell. This allows us to later find the cell in our code.

table-view-cell-settings
Apple provides some styles for the cells. However, you can make your very own subclass. But we’ll get to that in the next tutorial.

Now we need our code. You might think that we just have a file for a ViewController and you are right that file is still left from the beginning. So you can just delete it. Xcode will ask you if you want to move it to trash our just delete the reference. We want to send it straight to the bin. So select Move to Trash. After that we have to create a new file to interact with our TableViewController. So go ahead and create a new CocoaTouch Class as a subclass of UITableViewController.

table-view-new-file
Create a new file in the TableViewIntroduction folder. Just like you did last time with the SecondViewController

Now go back to the Interface Builder, because we need to tell the TableViewController which class will handle it. Again this is the same approach like in the last tutorial. Select the TableViewController and go to the Identity Inspector tab, left of the Attributes Inspector tab. And in the custom class section you put TableViewController.

table-view-custom-class
Most of the time you want to use a UI element you have to assign a class which handles it.

The only thing left to do is to embed our TableViewController in a NavigationController. This is can be done by Xcode automatically. Just go to Editor in Xcode’s Menu Bar. Then under Embed In you select NavigationController. The Storyboard automatically sets the NavigationController as Initial View Controller. This time we won’t need a custom class because the NavigationController does exactly what we want it to do.

Handling a TableView. Not that difficult.

Now you can switch back to your TableViewController.swift file. Luckily, Xcode already created a lot of custom functions for us to use. Some of them are commented out by surrounding them with ” /* */ ” for multiple lines. ” // ” just comments one line. 

(1) let mountains = ["Mount Everest", "Aconcagua", "Denali", "Kilimanjaro", "Mount Elbrus", "Mount Vinson", "Puncak Jaya"]
(2) let elevations = [8848, 6961, 6194, 5895, 5642, 4892, 4884]

   // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
(3) return 1
    }

   override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       // #warning Incomplete implementation, return the number of rows
(4)    return mountains.count
   }

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
(5)    let cell = tableView.dequeueReusableCell(withIdentifier: "mountainCell", for: indexPath)
       // Configure the cell...
(6)    cell.textLabel?.text = mountains[indexPath.row]
(7)    cell.detailTextLabel?.text = "\(elevations[indexPath.row])m"
       return cell
   }
  1. We create an array of our mountain names. The names are ordered from tall to short.
  2. We also need an array to store each mountains elevation.
  3. To make sure that the TableView displays anything you have to change the number of sections to 1.
  4. We need exactly 7 cells. But rather than hard-coding it we will make it dynamic by counting the elements in the mountains array.
  5. Here we will need the Identifier we set earlier in the Interface Builder. Remember we changed it to mountainCell.
  6. Because we chose the Right Detail style we have two Label we can use to display data. textLabel is the one on the left. You can access the current row’s number with indexPath.row and that in turn can be used to access the Array.
  7. The same applies to the detailTextLabel, which is on the right. Through String Interpolation you can display the numbers as text.

And done! Your first TableView.

You can now try your app. It will display the mountain with its elevation. Really cool!

table-view-mountain-app
Now you have your own list of the Seven Summits. How neat is that!

What you’ve learned.

Today you learned about one of the most important UI elements in today’s mobile development world. You know how to replace a ViewController with a TableViewController. You now know how to set an Initial View Controller for the Storyboard. You also learned how to embed an existing controller in an NavigationController. You can set a lot of settings for the TableView in code and you know how to make your TableView dynamic. In the end you learned how to display the data you got in each cell.

Not enough?

If you don’t have enough I have another task you can try. Why don’t you try out the other styles Apple provides. You can also try to make a longer list. And be sure to check out which settings can be set for the TableView in the Interface Builder, there are a lot.

 

Happy Coding!

Michael.

 

All the files of the finished project can be downloaded here.

 


Did you find this tutorial helpful?
Do you want to learn more about iOS and all its in and outs?
Tell me in the comments what you would like to see covered.

Leave a Reply