TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SWIFT

Swift UITableView Example: UITableViewDataSource

Use a UITableView and implement UITableViewDataSource and UITableViewDelegate. Add text rows to a TableView.
UITableView. A spreadsheet contains numbers. Tables are everywhere: they contain rows and columns and cells of data. We use text, pictures, numbers.
Let us start. Please create a Single View Application in Xcode. Open the object library. Drag the Table View to your iPhone window.
Table View. The text "Table View Prototype Content" will appear. Just ignore this placeholder text. Now open the ViewController.swift file—here we will place our important logic.
Example ViewController: Swift // // ViewController.swift // ExampleTime12 // // ... // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
Add UITableViewDataSource. Now add some protocols to the class by typing them in. We will add the minimum required ones to keep this tutorial simple.

Protocols: Please type in UITableViewDataSource and UITableViewDelegate. Then type (or paste) the needed methods.

Methods: Add tableView—a dummy implementation can be used for the initial code. Add the second tableView also—it returns an Int.

Example UITableViewDataSource: Swift // // ViewController.swift // ExampleTime12 // // ... // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } }
Add outlet. Please select the Table View and press control. Drag the mouse to the ViewController.swift text file in Xcode. Type a name (I like "simpleTable") and click Connect.

Tip: A field of type UITableView will appear in your ViewController class. This will be needed for setup logic.

Add Table Cell. We are not done yet. But we are getting there. Please use the object library again to add a Table Cell—drag it to your Table View.
Add identifier. Please click on the Table Cell in Xcode and then find the attributes pane. Type in an identifier for reusable cells.

Note: As a performance optimization, UITableCells can be reused. This avoids many allocations and makes programs better.

Set dataSource, delegate. Here is the magic trick. We add an example implementation of UITableViewDataSource and UITableViewDelegate to ViewController. We add a string array to display.

Arrays: We use an "animals" array containing the names of three animals. This is displayed in the UITableView.

Array

ViewDidLoad: In this func we set the simpleTable's dataSource and delegate to the current class instance. Self means the current instance.

Cell: We use dequeueReusableCellWithIdentifier with the "Example" identifier we set for our Table Cell.

Example tableView func: Swift // // ViewController.swift // ExampleTime12 // // ... // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var simpleTable: UITableView! var animals = ["cat", "frog", "parrot"] override func viewDidLoad() { super.viewDidLoad() // Use this class as the dataSource and delegate. self.simpleTable.dataSource = self; self.simpleTable.delegate = self; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Get reusable cell. if let cell = tableView.dequeueReusableCellWithIdentifier("Example") { // Set background color. cell.backgroundColor = UIColor.greenColor() // Set text of textLabel. // ... Use indexPath.item to get the current row index. if let label = cell.textLabel { label.text = animals[indexPath.item] } // Return cell. return cell } // Return empty cell. return UITableViewCell() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Use length of array a stable row count. return animals.count } }
More notes, tableView. Look at the first tableView func again. We access the "textLabel" property from the cell and then assign its "text" value to a string.

Optionals: We use the Swift feature that binds optionals with "if let" to access optional values. This is safe and easy.

Optional Binding

UIColor: For our program we use a beautiful green color for each Table Cell, creating a professional design.

UIColor

IndexPath: We use indexPath.item to get the index of each row in the first tableView func. This is an Int.

Int

NumberOfRowsInSection: This returns the row count. We just use our array's count property. In this example that is equal to 3.

Run simulator. If the alignment of the planets is correct our program will work. A green table with 3 rows and text labels equal to the Swift array's elements will appear.
A summary. With UITableView, UITableViewCell, UITableViewDataSource and UITableViewDelegate we become confused. But this tutorial brought us to a working Table View.
© TheDeveloperBlog.com
The Dev Codes