John Datserakis

John Datserakis

How to build a simple UITableView using Swift and Xcode 6.1.1 - With Tag support

Today I will be showing you how I create a UITableView using Swift and Xcode 6.1.1.

This particular method will also teach you how to control UILabels and UIImageViews in your Storyboard from your Swift code. This is advantageous when you have a thumbnail that might change or some JSON information you're parsing out. Anyways, let's get started.

Getting started

The first thing you want to do is boot up Xcode and create a new project. Choose Single View Application from the initial screen, and set the product name to whatever you want, I'll be using "Table View Tester".

Once your project is set up, run it and make sure you have a white screen showing in your simulator. Perfect. It may not be much yet - but we'll change that.

Click in the ViewController.swift file on the left side of screen to open it. Right now it's filled with the initial code and methods needed to run. Let's go ahead and add...

1@IBOutlet weak var tableMain: UITableView?

...right underneath where it says class ViewController, but above the viewDidLoad function. Here we are adding a variable named tableMain. You may be wondering what the question mark is about. To put it simply, our table view is considered optional in the situation and Swift requires a question mark in this instance. In order to learn more about optionals and the unwrapping of variables, check here.

Now that we created our UITableView variable, we must conform to the UITableView protocols. This may be a strange concept if you're new to programming, but essentially we need to register with the system before we can make use of something like a UITableView. Go ahead and add UITableViewDelegate and UITableViewDataSource like in the picture below.

Once you've done that, you'll find that Xcode may be complaining about missing some functions. Don't worry, we'll be adding those now. Here is the first required function:

1func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 2 // Here we create our initial UITableViewCell variable. 3 var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell 4 5 // Here we see if we should be creating a fresh cell or reusing one. 6 if (cell == nil) { 7 8 // Creating cell 9 cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") 10 11 } 12 13 // By here, we know the cell has been created. 14 var label_title : UILabel? = self.view.viewWithTag(1) as? UILabel; 15 label_title?.text = "Sample text from code" 16 17 // Thumbnail Setup 18 var label_thumbnail : UIImageView? = self.view.viewWithTag(2) as? UIImageView; 19 label_thumbnail?.image = UIImage(named: "monkLogo250") 20 21 return cell! 22}

Here's what that looks like in my project:

It seems like a lot of code, but it's really simple once you break it down. First we implement the cellForRowAtIndexPath function - something you'll be seeing a lot of as UITableViews are used constantly. We create a variable named cell and assign its Identifier to "Cell". Then, we check to see if cell is nil. If it is, we create the cell ourselves using the default UITableViewCellStyle.

This is how we are physically creating the cells as they are needed. Below that we assume that we are dealing with non-nil cells and can create our label title and label thumbnail appropriately. Change "monkLogo250" to the name of whatever small picture you want to add to your project. To read more on how UITableView works, check here.

To allow us to manipulate items in the Storyboard from the code we assign tags. As you can see, we set the title to tag 1 and the thumbnail to tag 2. At the end of this function we return our newly created variable.

Next we implement the numberOfRowsInSection function. This is where we specify how many rows we want to show in our UITableView. We'll show three.

1func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 2 return 3 3}

Alright, so now we're done with the hard part and it's time now to hook everything up in the Storyboard. On the left side of your project, click Main.storyboard to show the Storyboard for your project.

What you'll see is a blank canvas. This is our View Controller's scene - the same one we were working on in ViewController.swift. What you want to do is is drag a Table View out from the object library on the bottom right of your screen and add it to our scene.

Once you center it in the scene, leave the Table View selected. While the Table View is selected, hit the little button below the scene with the triangle between two lines and select Reset To Suggested Constraints. Remember this action -  I use it all the time.

In the Document Outline portion of the storyboard, right click on where it says Table View and connect the delegate and the dataSource to the View Controller.

If you're not sure where to do that, it's the first of three icons at the top of View Controller's Storyboard scene. While you're at it, right click again on the table view and drag New Referencing Outlet to the View Controller and select tableMain from the popup.

More Table View work

Next, while you have the Table View selected, open up your Attributes inspector and change Prototype Cells to 1.

Now, select the Cell in the Storyboard and change the Style to Basic and set the Image to the small image you have imported into your project.

Almost there, just a little bit more.

Now the table view is connected, but our tags aren't set up yet. Select the Title label in the Storyboard and go to the Attributes inspector. About half way down the inspector you will see Tag. Set it to 1. Do the same for the thumbnail image you added a step back, except set its Tag to 2. For a finishing touch, select Editor from the Menu Bar and then Embed In, then Navigation Controller.

This a great and easy way to add a Navigation Bar and Navigation Controller to a Storyboard Screen. Because we've now set this up, we can double-click in the newly-formed navigation bar of View Controller and set a title. I used "Table View Tester".

Wrapping up

That's it! Run the application and you should see that any string you add in your code will show in our UILabel. The same goes for our thumbnail's image by changing the UIImage.

This is how you would go about fetching thumbnail images from a JSON set and setting a different one for each cell. Also, you can use as many UILabels as you application needs by adding more labels and more tags.

Thanks for joining me and as always if you have any further questions or see any mistakes, I'd love to hear the feedback. Happy Swifting!

Home