Eric
Eric

Reputation: 61

How to set header or footer background color in UITableView

Forward: I had this question and didn't find much on SO about it except a bit of related information here, but I eventually figured it out, and thought there ought to be a clearer question and solution posted on SO for others to find, so I'm asking it here and then responding to my own post with what worked great for me (although someone is always welcome to critique).

Question: How can I change the background color for headers or footers in a UITableView?

Upvotes: 0

Views: 1007

Answers (2)

Anıl Sözeri
Anıl Sözeri

Reputation: 96

You can drag and drop in your storyboard UIView for header/footer view.

After that you can edit as you wish in the attribute inspector.

Also you can manipulate with UITableView's delegate functions for header/footer view.

Upvotes: 0

Eric
Eric

Reputation: 61

The code below is for changing the background color of the footer. For the header, it's the same, but should be posted in the willDisplayHeaderView delegate method.

func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
    if let footer = view as? UITableViewHeaderFooterView {
        footer.contentView.backgroundColor = UIColor.white
    }
}

Note: I originally thought setting footer.backgroundView.backgroundColor = UIColor.white would work, but it did not for me. I suspect it was because the contentView was covering it up, and this would have to be set to clear first, before the backgroundView showed. Therefore, I figured it was easiest just to set the color of the content view directly.

Upvotes: 4

Related Questions