Dynamic Cell Heights

Currently, the cells have a fixed height of 65 points. It is much better to allow the content of the cell to drive its height. That way, if the content ever changes, the table view cell’s height can change automatically.

You can achieve this goal, as you have probably guessed, with Auto Layout. The UITableViewCell needs to have vertical constraints that will exactly determine the height of the cell. Currently, ItemCell does not have sufficient constraints for this. You need to add a constraint between the two left labels that fixes the vertical spacing between them.

First, open Main.storyboard. Control-drag from the nameLabel to the serialNumberLabel and select Vertical Spacing.

Next, open ItemsViewController.swift and update viewDidLoad() to tell the table view that it should compute the cell heights based on the constraints.

Listing 10.5  Using dynamic cell heights (ItemsViewController.swift)

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.rowHeight = 65
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 65
}

UITableView.automaticDimension is the default value for rowHeight, so while it is not necessary to add, it is useful for understanding what is going on. Setting the estimatedRowHeight property on the table view can improve performance. Instead of asking each cell for its height when the table view loads, setting this property allows some of that performance cost to be deferred until the user starts scrolling. Ultimately, though, setting an estimated row height value is what triggers the dynamic row height system.

Build and run the application. It will look the same as it did before. In the next section, you will learn about a technology called Dynamic Type that will take advantage of the automatically resizing table view cells.

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

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