Filling a TableView with Data

If you look at the apps that come with an iPhone or iPad, you’ll notice that one common feature is the use of rows of data such as viewing a list of email messages in the Mail app. Whenever you see multiple rows of data that you can scroll up or down on the screen, chances are good it’s a table view.

The basic idea behind a table view is to create a dynamic list of information on the screen that users can scroll through and tap to select. The first step is to put a table view (not a table view controller) on a view (the user interface).

Once you have a table view on your user interface, the next step is to write the actual code to store data in that table view. First, you must make sure your class adds the UITableViewDelegate and UITableViewDataSource as follows:

                                        // 1. Add UITableViewDelegate and UITableViewDataSource to the class file
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

Second, you need to define your data. The simplest example is to use an array such as:

    // 2. Define data to display in the table such as an array
    var cats = ["Bo", "Scraps", "Tasha", "Nuit", "Oscar", "Mayer"]

To physically access and display data in a table view, you need to create an IBOutlet between the table view on the user interface and your actual Swift class file like this:

    // 3. Create an IBOutlet for the table view on the user interface
    @IBOutlet weak var tableOfCats: UITableView!

Fourth, you need to define which file will act as the table view’s delegate and data source. If you store everything in a class file, you can just make the class file the delegate and data source. One way to do this is by control-dragging from the table view on the user interface to the view controller icon. However a more visible way to do this is to define this in Swift code like this:

        // 4. Define the Swift view controller file as the table view's delegate and data source
        tableOfCats.delegate = self
        tableOfCats.dataSource = self

Now you need to define how many items will appear in the table view. Since this number can vary, you need code that will automatically count the number of items to display. If you’re storing data in an array, you can use the array count method to define the total number of items to display in a table view like this:

    // 5. Define how many items will appear in the table view
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cats.count
    }

Finally, you need to give the cell, in your table view, a unique identifier name such as “myCell” so you can identify it. Then the final step is to use this cell to fill with data. The first line of the following function tells the table view to use the cell identified by its name.

The second line says to store an array element into the text property of the cell.

The third line says to show that data in the cell of the table view, so the whole function looks like this:

   // 6. Define the actual data that appears in each row of the table view
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // "myCell" below is the identifier name of the table view's prototype cell
        let showData = tableView.dequeueReusableCellWithIdentifier("myCell")
        
        showData?.textLabel!.text = cats[indexPath.row]
        
        return showData!
        
    }

If you want to identify which table row the user tapped on, you need to write another function like this:

    // 7. Identifies which table row the user selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
        
        print(currentCell.textLabel!.text!)
    }

So if you put a table view on your user interface and name the cell in that table view as “myCell”, the whole code looks like this:

import UIKit

                                        // 1. Add UITableViewDelegate and UITableViewDataSource to the class file
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    
    // 2. Define data to display in the table such as an array
    var cats = ["Bo", "Scraps", "Tasha", "Nuit", "Oscar", "Mayer"]

    
    // 3. Create an IBOutlet for the table view on the user interface
    @IBOutlet weak var tableOfCats: UITableView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 4. Define the Swift view controller file as the table view's delegate and data source
        tableOfCats.delegate = self
        tableOfCats.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // 5. Define how many items will appear in the table view
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cats.count
    }
    
    // 6. Define the actual data that appears in each row of the table view
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // "myCell" below is the identifier name of the table view's prototype cell
        let showData = tableView.dequeueReusableCellWithIdentifier("myCell")
        
        showData?.textLabel!.text = cats[indexPath.row]
        
        return showData!
        
    }
    
    // 7. Identifies which table row the user selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let currentCell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
        
        print(currentCell.textLabel!.text!)
    }

}
May 27th, 2016 by
HTML Snippets Powered By : XYZScripts.com