A Beginners Guide to Populating and Using TableViews in iOS

Share this article

Using a table has always been a popular method to display and layout data, from spreadsheets to web pages, and now of course, Mobile apps.

In this tutorial I will show you how to use and populate iOS’s TableViews with data.

Getting Started

First create a new Xcode project, choosing the Master-Detail Application template.

Create New Project

Click Next and add a name for the project. Set the project options as shown in the screenshot below and click Next.

Set Name for Project

If you run the project, you will see a table view with a + button on the right side of the top bar. This adds the current date and time in a new row of the table each time the user taps it. If you tap on one of the rows, a detail view will show a label with the date of the selected row.

Table View

Table Set Up

Open the MasterViewController.swift file from Project Navigator. It’s an instance of the UITableViewController class and controls the functionality and data of the table view.

The viewDidLoad function sets the + button and a split view controller. The split view controller will only work on iPads.

The numberOfSectionsInTableView function returns the number of sections in the table. If you do not add any categorization, it will return 1.

The tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int function returns the number of rows the table has in each section. In a table view, data is in an array structure wand presented in the table view. In this case the objects array.

The tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell function creates each cell in the table, setting text and other attributes. The indexPath.row value provides the integer value of the index.

The tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool function returns a value defining wether the cell is editable or not.

The tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) function changes the style of a cell and includes boilerplate code for delete and insert styles.

Interacting with the Table

Until this point you have learned how to setup a tableview and which functions it needs to work.

The class also contains this function:

func insertNewObject(sender: AnyObject) {
  objects.insert(NSDate(), atIndex: 0)
  let indexPath = NSIndexPath(forRow: 0, inSection: 0)
  self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}

This function runs when the user taps the + button and adds the current date object to the objects array and thus the first row of the tableview.

The Detail View

The Main.storyboard file handles most of the detail view. In the screenshot below, you can see the selected segue handles the selection of the row and presents it in the detail view.

Details view segue

When a user selects a row, the override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) function of the MasterViewController class runs:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "showDetail" {
      if let indexPath = self.tableView.indexPathForSelectedRow {
          let object = objects[indexPath.row] as! NSDate
          let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
          controller.detailItem = object
          controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
          controller.navigationItem.leftItemsSupplementBackButton = true
      }
  }
}

This function checks if the segue is the detail view and sets the detail view properties according to the selected row.

Fill the Table with Content

Now fill the table with static content from an array. To do this, first remove the following lines from the override func viewDidLoad() function of MasterViewController.swift.

self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton

This removes the + and edit buttons.

Now add the following lines to the same function.

objects.insert("January", atIndex: 0)
objects.insert("February", atIndex: 1)
objects.insert("March", atIndex: 2)
objects.insert("April", atIndex: 3)
objects.insert("May", atIndex: 4)
objects.insert("June", atIndex: 5)
objects.insert("July", atIndex: 6)
objects.insert("August", atIndex: 7)
objects.insert("September", atIndex: 8)
objects.insert("October", atIndex: 9)
objects.insert("November", atIndex: 10)
objects.insert("December", atIndex: 11)

These lines populate the objects array that feeds the table view with the names of all the months in a year as string values.

In the tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell function change the following 2 lines:

let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description

to:

let object = objects[indexPath.row] as! String
cell.textLabel!.text = object

And in override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { change:

let object = objects[indexPath.row] as! NSDate

to:

let object = objects[indexPath.row]

These lines are changed because now the values of the objects array are string values and you can instantly set the cell.textLabel!.text value to the objects[indexPath.row] because it’s a string.

Run the app and you should see the table filled with the months of the year. When you tap on a row of the table, the detail view shows, presenting a label of the month name.

Final Application

You can find the final project with the changes you made on GitHub.

This was a basic introduction to the tableview and they have a lot of potential, if you’re interested in learning more, SitePoint has more advanced tutorials and the iOS developer library has some great next steps.

Any questions or comments? Please let me know below.

Frequently Asked Questions (FAQs) about Populating and Using TableViews in iOS

How can I add a custom cell to my TableView in iOS?

To add a custom cell to your TableView, you first need to create a new UITableViewCell subclass. This subclass will define the properties of your custom cell. After creating this subclass, you can then use the ‘dequeueReusableCell’ method to create an instance of your custom cell. You can then configure the properties of this cell in your ‘cellForRowAtIndexPath’ method. Remember to set the identifier of your custom cell in the storyboard to match the one you use in your code.

How can I handle user interaction with my TableView?

User interaction with a TableView can be handled using the ‘didSelectRowAtIndexPath’ method. This method is called whenever a user taps on a cell in your TableView. You can use this method to perform actions based on the selected cell. For example, you can use it to navigate to a new view controller that displays more detailed information about the selected item.

How can I add a header or footer to my TableView?

Headers and footers can be added to a TableView by implementing the ‘viewForHeaderInSection’ and ‘viewForFooterInSection’ methods respectively. These methods return a view that will be used as the header or footer for each section in your TableView. You can customize these views to display any content you want.

How can I update the data in my TableView?

To update the data in your TableView, you need to update the data source of your TableView and then call the ‘reloadData’ method. This method will cause your TableView to call its data source methods again and update its content accordingly.

How can I add a search bar to my TableView?

A search bar can be added to a TableView by adding a UISearchBar to your storyboard and then implementing the UISearchBarDelegate methods in your view controller. You can use these methods to update your data source and TableView based on the user’s search query.

How can I add swipe actions to my TableView cells?

Swipe actions can be added to TableView cells by implementing the ‘trailingSwipeActionsConfigurationForRowAt’ and ‘leadingSwipeActionsConfigurationForRowAt’ methods. These methods return a UISwipeActionsConfiguration object that defines the actions that should be performed when the user swipes on a cell.

How can I add multiple sections to my TableView?

Multiple sections can be added to a TableView by implementing the ‘numberOfSectionsInTableView’ method. This method should return the number of sections you want in your TableView. You can then use the ‘numberOfRowsInSection’ method to specify the number of rows in each section.

How can I sort the data in my TableView?

Data in a TableView can be sorted by updating your data source to be in the desired order and then calling the ‘reloadData’ method. You can sort your data source using the ‘sort’ method provided by Swift’s Array class.

How can I add a refresh control to my TableView?

A refresh control can be added to a TableView by creating a UIRefreshControl object and setting it as the TableView’s ‘refreshControl’ property. You can then use the ‘valueChanged’ event of the refresh control to update your data source and TableView when the user performs a pull-to-refresh action.

How can I add an index list to my TableView?

An index list can be added to a TableView by implementing the ‘sectionIndexTitles’ method. This method should return an array of strings that will be used as the titles for the index list. You can then implement the ‘sectionForSectionIndexTitle’ method to navigate to the appropriate section when the user selects a title from the index list.

Petros DemetrakopoulosPetros Demetrakopoulos
View Author

Petros Demetrakopoulos is 19 years old and is a CS Student in Athens University of Economics and Business. He has been coding since the age of 12 and during the last 6 years developing iOS apps and games with 9 published on App Store.

applechriswioslayouttables
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week