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.

Open Main.storyboard. Control-drag from the nameLabel to the serialNumberLabel and select Vertical Spacing.

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

override func viewDidLoad() {
    super.viewDidLoad()

    // Get the height of the status bar
    let statusBarHeight = UIApplication.shared.statusBarFrame.height

    let insets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0)
    tableView.contentInset = insets
    tableView.scrollIndicatorInsets = insets

    tableView.rowHeight = 65
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 65
}

UITableViewAutomaticDimension 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.

Build and run the application. The application 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