Understanding table views

The Let's Eat app uses a table view in the Locations screen to display a list of restaurant locations. A table view presents table view cells using rows arranged in a single column.


To learn more about table views, visit https://developer.apple.com/documentation/uikit/uitableview.

To provide data to be displayed by a table view, view controllers for a table view must conform to the UITableViewDataSource protocol and implement the required methods.


To learn more about the UITableViewDataSource protocol, visit https://developer.apple.com/documentation/uikit/uitableviewdatasource.

To allow users to interact with a table view, view controllers for a table view must conform to the UITableViewDelegate protocol and implement the desired methods.


To learn more about the UITableViewDelegate protocol, visit https://developer.apple.com/documentation/uikit/uitableviewdelegate.

To learn how table views work, you'll implement a view controller subclass that controls a table view in your TableViewBasics playground. Since there is no storyboard in the playground, you can't add the UI elements using the Object library, as you did in the previous chapters. Instead, you will do everything programmatically. Do the following steps:

  1. Remove all the existing code from the playground. Then, at the very top of the playground, add the following import statements:
import UIKit
import PlaygroundSupport

The first import statement imports the API for creating iOS applications. The second allows the playground to display a live view, which you will use to display the table view.

  1. Type Return and then add the following code:
class TableViewExampleController: UIViewController {

}

This is the declaration for the TableViewExampleController class. It is a subclass of UIViewController, which is a class that Apple provides to manage views on the screen.

  1. Add the following code inside the curly braces:
var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]
  1. The complete code should look as follows:
class TableViewExampleController: UIViewController {
var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]
}

The first line adds an optional property to the tableView class, which is of the UITableView type. A UITableView instance, or table view, displays a single column of rows on the screen, and each row contains a UITableViewCell. Before it can do so, it needs to know how many rows to display and what to put in each row.

The second line creates an array called names. This is the model object that will be used to provide data to the table view. To do so, you will designate TableViewExampleController as the data source for the table view and make it adopt the UITableViewDataSource protocol.

  1. To make TableViewExampleController adopt the UITableViewDataSource protocol, type a comma after the superclass name, UIViewController, and type UITableViewDataSource. When you are done, you should have the following code:
class TableViewExampleController: UIViewController, UITableViewDataSource {
var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]
}

This protocol has two required methods. The first one, tableview(_:numberOfRowsInSection:), tells the table view how many rows to display, while the second one, tableView(_:cellForRowAt:), tells the table view what to put in each row. 

An error will appear because you haven't implemented the two required methods yet:

  1. Click the error icon. You should see the following error message:

  1. Click the Fix button to add the required methods to the class. Your code should look as follows:
class TableViewExampleController: UIViewController, 
UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
code
}

func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
code
}

var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]
}
  1. Rearrange the code so that the property declarations are at the top. It should look like this:
class TableViewExampleController: UIViewController, 
UITableViewDataSource {

var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]

func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
code
}

func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
code
}
}
  1. Inside tableView(_:numberOfRowsInSection:), click the word code and type in return names.count. The modified method should look like this:
func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
return names.count
}

names.count returns the number of items inside the names array. Since there are three names in the names array, this will make the table view display three rows.

  1. Inside tableView(_:cellForRowAt:), click the word code and type the following:
let cell = tableView.dequeueReusableCell(withIdentifier:   
"Cell", for:indexPath) as UITableViewCell
let name = names[indexPath.row]
cell.textLabel?.text = name
return cell
  1. The completed method should look as follows:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"Cell", for:indexPath) as UITableViewCell
let name = names[indexPath.row]
cell.textLabel?.text = name
return cell
}

Let's go over how this method works, bit by bit:

  • let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for:indexPath) as UITableViewCellThis creates a new table view cell or reuses an existing table view cell and assigns it to cell. Imagine you have 1,000 items to display in a table view. You don't need 1,000 rows containing 1,000 table view cells—you only need just enough to fill the screen. Table view cells that scroll off the top of the screen can be reused to display items that appear at the bottom of the screen. To make sure you are using the right type of cell, you need to use a reuse identifier, which is set to Cell. The reuse identifier needs to be registered with the table view, and you will do that later.
  • let name = names[indexPath.row]The indexPath returns the section and row number of a particular row in a table view. The first row has an indexPath containing section 0 and row 0. indexPath.row returns 0 for the first row, so we get the first item in the names array and assign it to the name constant.
  • cell.textLabel?.text = nameThis assigns name to the text property of the table view cell's textLabel.
  • return cellThis returns the cell, which is then displayed on the screen.

This process is repeated for the number of cells given in the first method, which, in this case, is 3.

  1. Your file should look as follows:
class TableViewExampleController: UIViewController, 
UITableViewDataSource {

var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]

func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return names.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"Cell", for:indexPath) as UITableViewCell
let name = names[indexPath.row]
cell.textLabel?.text = name
return cell
}
}

Now that you have completed the declaration of TableViewExampleController, you will write a method to create an instance of it. Follow these steps to do so:

  1. Type in the following code after the property declarations:
func createTableView() {
self.tableView = UITableView(frame:CGRect(x: 0, y: 0, width:
self.view.frame.width, height:
self.view.frame.height))
self.tableView?.dataSource = self
self.tableView?.backgroundColor = .white
self.tableView?.register(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
self.view.addSubview(self.tableView!)
}

This declares a new method, createTableView(). Here's how it works:

  • self.tableView = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))This creates a new instance of UITableView that is exactly the same size as its enclosing view, and assigns it to tableView.
  • self.tableView?.dataSource = selfThis tells the table view that its data source is TableViewExampleController.
  • self.tableView?.backgroundColor = .whiteThis sets the table view's background color to white.
  • self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")This sets the reuse identifier for the table view cells to "Cell". This reuse identifier will be used in the tableView(_:cellForRowAt:) method to identify the cells that can be reused.
  • self.view.addSubview(self.tableView!)This adds the table view as a subview to the view of TableViewExampleController.

Now, you need to call this method. UIViewController has a method, viewDidLoad(), that is called when its view is loaded, and this is the perfect method to override to call createTableView()

  1. Type in the following code, just above the createTableView() method:
override func viewDidLoad() {
super.viewDidLoad()
createTableView()
}

This creates a table view and adds it as a subview to the view of the TableViewExampleController instance. The data source methods are then used to determine how many table view cells to display, as well as what to put in each table view cell.  tableView(_:numberOfRowsInSection:) returns 3, so three rows are displayed. tableView(_:cellForRowAt:) sets the text of each cell to the corresponding name in the names array.

  1. Your completed code should look like this:
import UIKit
import PlaygroundSupport

class TableViewExampleController: UIViewController,
UITableViewDataSource {

var tableView:UITableView?
var names:[String] = ["Kajal","Akhil","Divij"]

override func viewDidLoad() {
super.viewDidLoad()
createTableView()
}

func createTableView() {
self.tableView = UITableView(frame:CGRect(x: 0, y: 0,
width: self.view.frame.width, height:
self.view.frame.height))
self.tableView?.dataSource = self
self.tableView?.backgroundColor = .white
self.tableView?.register(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
self.view.addSubview(self.tableView!)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return names.count
}

func tableView(_ tableView: UITableView, cellForRowAt
indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"Cell", for:indexPath) as UITableViewCell
let name = names[indexPath.row]
cell.textLabel?.text = name
return cell
}
}
  1. Now, it's time to see what it does. Type the following after all the other code in the playground:
PlaygroundPage.current.liveView = TableViewExampleController()

This command creates an instance of TableViewExampleController and displays its view in the playground's live view.

  1. Run the playground. If you don't see the table view, click the Adjust Editor Options button shown in the following screenshot:

  1. Make sure Live View is selected from the pop-up menu:

  1. You will see the table view displaying a table with three rows containing names, as shown in the following screenshot:

Great! Now that you know how table views work, let's complete the implementation for the Locations screen. You'll start by creating a view controller for this screen so that it can manage what the table view will display.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.166.98