jesper87 jesper87 - 16 days ago 5
Swift Question

Swift table view background for empty rows and section header

I have a table view controller with a header that I want to give a certain background color. I also want the text "John Doe" to be perfectly aligned with the menu icon, as you can see in the following screenshot:

Screenshot

To make sure "John Doe" is perfectly aligned with the menu icon, and to set the correct background color, I use the following code:

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let inset = UIEdgeInsetsMake(20, 0, 0, 0);
tableView.contentInset = inset

tableView.backgroundColor = UIColor(red: 0.63, green: 0.64, blue: 0.66, alpha: 1.0)
}


The status bar ("Carrier / 8:57 AM") height is 20, so the inset is needed to make sure John Doe is correctly aligned.

That works great, but now the empty rows are also in this background color. I have tried adding an empty view under the "Logout" button and give it the same color as the rows, but I can't seem to stretch this all the way to the bottom of the table view controller.

I have also tried setting the background color of the table header, but that won't work because then the status bar does not have the correct background color (because of the inset).

How can I make sure everything beneath the Logout button is in the same background color as the actual rows?

Edit: Setting the background color of the table results in this:
Screenshot

Now the status bar also has this color, because of the inset.

Answer

I couldn't get any of the suggestions to work, so I just create a table footer which fills up the rest of the screen:

var menuItems = ["Dial", "Settings", "CallHistory", "Logout"]
let headerHeight = CGFloat(64)
let cellHeight = 56

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    let inset = UIEdgeInsetsMake(20, 0, 0, 0)
    let totalMenuItemHeight = menuItems.count * cellHeight

    tableView.contentInset = inset
    tableView.backgroundColor = UIColor(red: 0.63, green: 0.64, blue: 0.66, alpha: 1.0)

    tableView.tableFooterView = UIView()
    tableView.tableFooterView!.backgroundColor = UIColor(red: 0.98, green: 0.98, blue: 0.98, alpha: 1.0)
    tableView.tableFooterView!.frame.size.height = tableView.frame.height - CGFloat(headerHeight) - CGFloat(totalMenuItemHeight)
}