Creating a Simple Table View in Swift

Table Views are the most important type of view in mobile development. You see them all the time in apps! Therefore it is essential to master them and be able to create Table Views on demand. So that’s what we are doing today!

What you will learn in this tutorial:

  • Creating a simple Table View
  • Customize cells
  • Creating Table View Controllers
  • Populating cells with data
  • Adding images to an app
  • Creating arrays

Note: This tutorial is updated for Swift 3

You might have seen something like this before.

airbnb-ios-1

This is actually a really fancy Table View. (Airbnb has a nice app) You can customize Table Views however you like!

Lets start with something simple though. We will be creating a Table View that looks like this.

Screen Shot 2016-08-17 at 11.08.15 PM

It is a simple app that just shows the name of a food item and a photo.

The first step is to create a new project in Xcode. Just create a new Single View Application.

Like so…

Screen Shot 2016-08-17 at 6.12.51 PM

The only really thing that matters to us here is the product name. Your organization name and identifier could be whatever you like. This will leave you with an empty project complete with the files: Main.storyboard and ViewController.swift.

Main.storyboard

Your Main.storyboard will look something like this.

Screen Shot 2016-08-17 at 11.22.08 PM.png

This is the storyboard! (if you haven’t figured that out by now). It is a great tools that allows us to design the user interface and flow of our app.

We see that there is one square that is labeled “View Controller” at the top. This square is called a scene which represents one screen of our app. The arrow to the left of it shows that this is the first scene users will see when they open our app.

The first step is to delete this scene. (We need a different type of scene for Table Views) Just click anywhere on it and hit delete.

In order to show a Table View we need a Table View Controller. This is a special type of scene specifically created for table views.

To add a Table View Controller to our scene we need to search for it in the Object Library which is located in a tab at the bottom right of Xcode. (Marked by the red square at the bottom right of the image below). If you cannot see this library make sure the “show utilities” button (shown inside the red triangle at the top right) is toggled on and the “object library” tab is selected at the bottom right.

Screen Shot 2016-08-17 at 11.31.22 PM

After searching for the Table View Controller in the Object Library, you now simply need to drag the Table View Controller from the object library into the storyboard.

Because we deleted our only scene that was created automatically for us earlier, we also removed the small grey arrow that indicated that the scene was the starting point for our app. We need to let Xcode know that this Table View Controller is the new starting scene for our app.

To do this, select the bar at the top of the Table View Controller in our storyboard. You should see some properties for the View Controller show up on the right when selected. Click on the “attributes” tab on the utilities panel on the right of Xcode. (highlighted by the small red square in the image below) then make sure that the “Is Initial View Controller” property is checked.

Screen Shot 2016-08-17 at 11.42.31 PM.png

Once it is checked, you should see that small grey arrow on the left of our view controller again. If not try scrolling around the storyboard, it should be there!

This attributes tab (where the “initial view controller” property is) allows you to set many different attributes for different views in your storyboard. You only need to select a view and its attributes can be modified there.

You might have been wondering what the white bar and the label that says “Prototype cells” in our Table View Controller is. Well, remember that this is a table view, and in swift, every row is called a cell. Xcode shows us what each cell in our TableView will look like by showing a prototype cell. Right now there is nothing in our cell so it is just a white bar.

So lets add some views to the cell!

To select the cell, it is easiest to click on it from the document outline. You can open it by clicking on the icon on the bottom left of the storyboard.

Screen Shot 2016-08-17 at 11.59.23 PM

Once you open the Document outline, expand the subviews until you can select the “Table View Cell”. Click on the attributes tab then you should see a property called “identifier”. Give your cell a unique identifier so that we may reference the cell in the code later. (My identifier is called “myCell”)

Screen Shot 2016-08-18 at 10.15.18 PM.png

Right next to the attributes tab on the top right is the “size inspector” tab. (The icon looks like a ruler) Select it to modify the size of our cell. Set the row height to 100.

Screen Shot 2016-08-18 at 12.03.13 AM

You might remember that each row in our target Table View has an image and a label that describes the image. It looks like this.

Screen Shot 2016-08-18 at 9.29.19 PM

Right now our prototype row is blank. We can drag some views into it to customize it.

In the object library (Where you searched for the Table View Controller) search for an “Image View” and drag it into the prototype cell.

After dragging it into the cell, try resizing it to look like the image below.

Screen Shot 2016-08-18 at 9.32.00 PM.png

Now try to do the same thing but with the “label” view.

Once you have a label and an image in our cell, we need to give them unique identifies so that we can find them in the swift code.

Select the label you just added and go back to the “Attributes” tab in the “utilities” panel. Under the sub-category named “view”, in the attributes tab, there is a property called “Tag”. The tag property of a view is a number that is unique to it. Go ahead and put any number you want in there. We will use that number to reference the label in the swift code. (I used the number 1000) Then do the same for the image view. Don’t forget that the tag needs to be unique. (I use the tag number 1001 for my image view)

Screen Shot 2016-08-18 at 9.35.07 PM.png

ViewController.swift

Now lets get to the code!

A View Controller is an essential part to creating our Table View. It is used to add the functionality to our app. (Or else the app would be full of buttons that don’t do anything!) You need a View Controller for every scene. Every time you create a new scene you should also be creating a new View Controller along with it.

Open up your ViewController.swift from the project navigator. It will look something like this.

Screen Shot 2016-08-18 at 9.45.42 PM.png

This is the template implementation for the ViewController that was created when you made you project.

Take a look at this line of code.

class ViewController: UIViewController{

This code is saying “create a class, name it ViewController, and make it of the type UIViewController”. We actually need to change the type from “UIViewController” to “UITableViewController”. (Xcode didn’t know we were making a table view)

The most important piece of code in our View Controller right now is the viewDidLoad() method. It looks like this.

override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

This method gets called after the view is initialized to inform the View Controller (so that it may do some configurations).

Add this code to your ViewController.swift.

screen-shot-2016-09-28-at-6-25-48-pm

Explaining the code:

var images = [UIImage]()

var foodNames = [String]()

This code creates two “arrays” (a fancy name for a list of things) named “images” and “foodNames”. After the view is loaded we populate the lists using the method “append”. We will add the images later.

Pretty simple!

Try adding the following code just above the last semicolon at the end of the ViewController.swift file. (Be careful with Xcode’s autocomplete, it could give you a similar but wrong function)

Screen Shot 2016-09-28 at 6.26.44 PM.png

These are the only blocks of code we need to get our Table View up and running. The blocks  of code are called functions (labeled with the keyword “func”) and each one has different uses. Let go over them.

tableView(numberOfRowsInSection)

Screen Shot 2016-09-28 at 6.27.47 PM.png

The first function is called by our Table View because it needs to know how many rows we are going to have in the Table View. So we return the number 3 to it.

tableView(cellForRowAtIndexPath)

Screen Shot 2016-09-28 at 6.27.51 PM.png

The second function is called for every cell that is loaded in the Table View. So if we told the first function there will be 3 rows, then this function will be called 3 times.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

What this function is saying is “let me implement the tableView function, particularly the function that will give me a reference to the table view, and tell me which row index is being loaded and I will give back a cell for you to use”. The tableView reference is a variable named “tableView” and the row index is named “indexPath”.

Each row in our table has an index starting from zero. For example, if there are 3 rows then their indexes will be 0, 1, and 2.

The goal of this second function is to create an instance of a cell

let cell = tableView.dequeueReusableCell(withIdentifier: “myCell”, for: indexPath)

This code is saying, “create or re-use a cell that has the identifier myCell, give it the position indexPath and store it in the variable cell“. The method dequeueReusableCellWithIdentifier creates or re-uses a cell for you to return. Why re-use? Well swift is smart enough to not initialize a view for each cell when someone is scrolling. (This would cause problems for a table view with thousands of cells of data) So it will give you one it already created but just put new information in it. That’s smart memory management!

Make sure to add the cell identifier you set earlier in the dequeueReusableCellWithIdentifier function. In this case my identifier is named “myCell”.

let label = cell.viewWithTag(1000) as! UILabel

let photo = cell.viewWithTag(1001) as! UIImageView

This code grabs creates a label and Image View by using their “Tag” value. Add in the tag properties you gave your Label and Image View.

label.text = foodNames[indexPath.row]

photo.image = images[indexPath.row]

This code is setting the label.text to an item in our food name list. The code “indexPath.row” refers to the index of the row we are creating a cell for in our Table View.

Our list of food names is indexed the same as the cells in our Table View. If there are 3 items in our list then they will be indexed as 0, 1, and 2. Therefore if we are creating a cell for index 0, then we will give the the name from the list at list index 0. The same occurs for our images.

return cell;

Lastly we are returning the newly configured and customized cell to our Table View for display!

Adding the Images

Adding image resources in Xcode is very easy.

Save these images to your computer by right clicking them and clicking “Save Image as…” (If you’re on chrome)

To add the images to the swift app, click on the “Assets.xcassets” folder in the project navigator. Click on the plus at the bottom left and then click on new image set.

You can then drag the images you downloaded into the “2x” square of your image set. Name the three images “meal1″, meal2”, and “meal3”.

Screen Shot 2016-08-18 at 10.43.44 PM.png

That’s it!

Run your app by clicking on the play button at the top of Xcode and you should see your new list in the emulated iphone.

Thanks so much for reading and please contact me if you have any questions or your List View still isn’t working. I will do my best to help!

Thanks,

Thomas Oropeza

www.thomasoropeza.com

thomasoropeza@gmail.com