Content Insets

As you have been running the application throughout this chapter, you might have noticed that the first table view cell underlaps the status bar (Figure 10.15). The interfaces for the applications you create fill up the entire window of the device. The status bar, if visible, is placed on top of the interface, so your interfaces must account for the placement of the status bar.

Figure 10.15  Table view cell underlapping status bar

Screenshot shows the output of the TableView, after updating the content inset. The Status Bar and the first row of the table have proper spacing.

To have the table view cells not underlap the status bar, you will add some padding to the top of the table view. A UITableView is a subclass of UIScrollView, from which it inherits the contentInset property. You can think of the content inset as padding for all four sides of the scroll view.

In ItemsViewController.swift, override viewDidLoad() to update the table view content inset.

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
}

The top of the table view is given a content inset equal to the height of the status bar. This will make the content appear below the status bar when the table view is scrolled to the top. The scroll indicators will also underlap the status bar, so you give them the same insets to have them appear just below the status bar.

Notice that you access the tableView property on the ItemsViewController to get at the table view. This property is inherited from UITableViewController and returns the controller’s table view. While you can get the same object by accessing the view of a UITableViewController, using tableView tells the compiler that the returned object will be an instance of UITableView. Thus, calling a method or accessing a property that is specific to UITableView will not generate an error.

Build and run the application. The table view cell content no longer underlaps the status bar when the table view is scrolled to the top (Figure 10.16).

Figure 10.16  Table view with adjusted content inset

Screenshot shows the output of the TableView, after updating the content inset. The Status Bar and the first row of the table have proper spacing.
..................Content has been hidden....................

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