Using ItemCell

Let’s get your custom cells onscreen. In ItemsViewController’s tableView(_:cellForRowAt:) method, you will dequeue an instance of ItemCell for every row in the table.

Now that you are using a custom UITableViewCell subclass, the table view needs to know how tall each row is. There are a few ways to accomplish this, but the simplest way is to set the rowHeight property of the table view to a constant value. You will see another way shortly.

Open ItemsViewController.swift and implement viewDidLoad() to set the height of the table view cells.

Listing 10.3  Setting a fixed row height (ItemsViewController.swift)

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = 65
}

Now that you have registered the ItemCell with the table view (using the prototype cells in the storyboard), you can ask the table view to dequeue a cell with the identifier "ItemCell".

In ItemsViewController.swift, modify tableView(_:cellForRowAt:).

Listing 10.4  Dequeuing ItemCell instances (ItemsViewController.swift)

override func tableView(_ tableView: UITableView,
                        cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Get a new or recycled cell
    let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell",
                                             for: indexPath)

    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell",
                                             for: indexPath) as! ItemCell

    // Set the text on the cell with the description of the item
    // that is at the nth index of items, where n = row this cell
    // will appear in on the tableview
    let item = itemStore.allItems[indexPath.row]

    cell.textLabel?.text = item.name
    cell.detailTextLabel?.text = "$(item.valueInDollars)"

    // Configure the cell with the Item
    cell.nameLabel.text = item.name
    cell.serialNumberLabel.text = item.serialNumber
    cell.valueLabel.text = "$(item.valueInDollars)"

    return cell
}

First, the reuse identifier is updated to reflect your new subclass. Then, for each label on the cell, you set its text to some property from the appropriate Item.

Build and run the application. The new cells now load with their labels populated with the values from each Item.

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

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