Table views on any mobile platform are the workhorse of any application. To be a good developer you need to make table views easily. Tables in iOS use the
UITableView
class to do so. This is a very powerful class with many features to make the tables you see in applications like Facebook, Instagram and Apple Music.
Because of the power and flexibility you have available to build tables, they are not as easy to create as a UIButton
or UILabel
. In this lesson I’ll introduce you to dynamic tables, and show you how to display a dynamic table. We’ll put together a menu of pizzas displaying the name of the pizza and the price.
Setting Up the Application
We’ll need to set up an application. This requires pretty robust model full of data. to save you the trouble of typing all that in, you can download this starter file: pizzatable_start.zip You can jump down to the Set up the Storyboard section, if you use the starter file. If you want to know what I did, or type it all in your self, I’ll very briefly tell you what’s in those files.
Create a new Single View project named PizzaTable. Use Swift as the language and Universal as the device. Once loaded, Press Command-N and make a new iOS cocoa touch class named MenuItems, subclassing NSObject. Create the class like this:
class MenuItems:NSObject{ let names:[String] = [ "Margherita Pizza","BBQ Chicken Pizza", "Pepperoni Pizza","Sausage Pizza", "Seafood Pizza","Sausage Deep Dish", "Meat Lover's Deep Dish","Veggie Lover's Deep Dish", "BBQ Chicken Deep Dish","Mushroom Deep Dish", "Tiramisu","Vanilla Ice Cream", "Apple Crostata","Hot Fudge Pizza", "Soft Drink","Coffee", "Espresso","Mineral Water"] let prices:[Double] = [ 7.95,11.49, 8.45,8.45, 12.75,10.65, 12.35,10.00, 16.60,11.25, 6.50,2.25, 6.50,9.75, 1.25,1.25, 3.50,3.75 ] let specials:[Bool] = [ false,true, false,false, false,false, true,false, false,true, false,false, false,true, false,false, true,false ] }
The class has three properties as arrays, the name of the menu Item, the price, and if it is a special or featured item.
We will not be using the ViewController.swift file. Select it, delete it and move it to the trash.
Set Up the Storyboard
In the storyboard,select the view controller scene and delete it. Find the Table View Controller in the object Library.
Drag a table view controller on the story board. In the Attribute Inspector, click on Is Initial View Controller.
In the document outline, select Table View Cell.
Select the menu in the attributes inspector for Style.You have several styles of menu.
We’ll place the pizza name on the left and the price in a smaller font on the right. Select Right Detail which has this style.
Under the style, you’ll find the identifier. Your code will use this identifier to find the cell. Name it cell
Press Command-N. Make a new iOS Cocoa Touch Class named TableViewController. There is a UITableViewClass
, but it is easier to not use it. The template has so many methods, it’s confusing. Instead, subclass UIViewController, and save the file. When the code appears, change the The UIViewController
subclass to UITableViewController
.
class TableViewController: UITableViewController {
Delete everything else but viewDidLoad
. The class should look like this:
class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } }
Go to the storyboard. In the document outline, select the Table View Controller Scene. Select the identity inspector and set the class to TableViewController.
Table View controllers don’t use outlets or actions if you set them up this way. Everything else is code.
Coding a Table View Controller
Coding a table view controller requires you to do three things: declare how many sections you have in your table, declare how many rows you have in each section, and populate each cell with data.
Before you do any of that, add the model. Go to the TableViewController.swift file. In the class add the following declaration:
var menuItems = MenuItems()
In many tables, there’s only one section. Our menu only has one section. For more on multiple sections, see my longer article Create Dynamic and Static Table View in Swift 3. We set the sections by overriding the numberOfsections(in tableView:)
method. All we do in the code is return 1
. Add this to the code:
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
To declare the number of rows for the sections, we override the tableView(_ tableView: NumberOfRowsInSection section:)
method. The number of rows are equal to the number of menu items. Add this:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.names.count }
The last required method populates the cell. This one is a bit more involved. Add the override to the class:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { }
This method returns a cell with the proper data. The parameters are the table view and the location in the table, know as the indexPath
. Type IndexPath
has two important components: the section and the row in that section. We’ll make a cell corresponding to the location indexPath in the table. Add this to the cellForRowAtIndexPath
method:
let cell = tableView.dequeueReusableCell( withIdentifier: "cell", for: indexPath)
cell
is of type UITableViewCell
, which has several properties you can use. The two most important are the UILabels
textLabel
and detailTextLabel
. They are labels which can get arranged differently depending on the style we use. You’ll take a value from the arrays in menuItem
, and display it on these labels.
You’ll need an index for the arrays. We can get that from the index path. Since this app has only one section, you can consider only the row. Add this to the method’s code:
let row = indexPath.row
This give us the row number in the table, and the index for the arrays. To set titleLabel
with the menu item, add this
cell.textLabel?.text = menuItems.names[row]
To set the price in the detail, add this:
let price = String(format:"%2.2f", menuItems.prices[row]) cell.detailTextLabel?.text = price
The app will highlight specials in green by changing the background color of the cell. Add this:
if menuItems.specials[row]{ cell.backgroundColor = UIColor.green } else { cell.backgroundColor = UIColor.white }
Finally return the cell
return cell
Build and run. You have a table you can scroll through.
This is only the beginning of tables. There’s a lot more to explore. Once you got this small last of how to build a table you might want to check out a few more tutorials on tables. Next you should dive a little deeper into tables with this post.
The Whole Code
Here is the code for this lesson. You can also download the completed project here:pizza table.zip
MenuItems.swift
// // MenuItems.swift // SwiftTableViewDemo // // Created by Steven Lipton on 10/1/16. // Copyright © 2016 Steven Lipton. All rights reserved. // import UIKit class MenuItems:NSObject{ let names:[String] = [ "Margherita Pizza","BBQ Chicken Pizza", "Pepperoni Pizza","Sausage Pizza", "Seafood Pizza","Sausage Deep Dish", "Meat Lover's Deep Dish","Veggie Lover's Deep Dish", "BBQ Chicken Deep Dish","Mushroom Deep Dish", "Tiramisu","Vanilla Ice Cream", "Apple Crostata","Hot Fudge Pizza", "Soft Drink","Coffee", "Espresso","Mineral Water"] let prices:[Double] = [ 7.95,11.49, 8.45,8.45, 12.75,10.65, 12.35,10.00, 16.60,11.25, 6.50,2.25,6.50, 9.75,1.25, 1.25,3.50,3.75 ] let specials:[Bool] = [ false,true, false,false, false,false, true,false, false,true, false,false, false,true, false,false, true,false] }
TableViewController.swift
// // TableViewController.swift // PizzaTable // // Created by Steven Lipton on 10/2/16. // Copyright © 2016 Steven Lipton. All rights reserved. // import UIKit class TableViewController: UITableViewController { var menuItems = MenuItems() override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.names.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let row = indexPath.row cell.textLabel?.text = menuItems.names[row] let price = String(format:"%2.2f", menuItems.prices[row]) cell.detailTextLabel?.text = price if menuItems.specials[row]{ cell.backgroundColor = UIColor.green } else { cell.backgroundColor = UIColor.white } return cell } override func viewDidLoad() { super.viewDidLoad() } }
Leave a Reply