Custom UITableViewHeaderFooterView with Interface Builder

So, one area that Apple needs to tighten up as it’s not clear and the Internet is also a bit divided on is setting up UITableViewHeaderFooterView objects in Interface Builder. Now, sadly you can’t do this in a table view in a Storyboard much like you’d design a prototype cell. No, but there are still ways to visually design these and write minimal code.

So you will have to subclass UITableViewHeaderFooterView and override -(UIView*)contentView. That’s the jist of it. You probably have to subclass it anyway because you have custom content!

@implementation MySettingsHeaderView
- (UIView*)contentView
  return self.subviews[0];

And then create a View NIB file, where the root view’s class is set to this above. The trick is that the first subview is going to be the contentView of the UITableViewHeaderFooterView, but strangely it is a readonly property. So that’s why you need to override.

Custom UITableViewHeaderFooterView in IB

So treat this view as the contentView and add everything to that. This way you can preserve AutoLayout stuff and avoid warnings like:

Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead

Then, all you do is in your viewDidLoad method, you put something like:

[self.tableView registerNib:[UINib nibWithNibName:@"MySettingsHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MyHeaderIdentifier"]; // though, be a good coder, and don't pass a hard-coded string, but define a constant for your header identifier!!

Boom! I love you too.

3 thoughts on “Custom UITableViewHeaderFooterView with Interface Builder

    • Double-check your spellings, and make sure the only view item in the XIB is a UIView, whose custom class you set yourself. Then make sure the file’s owner is not set, but the UIView subclass is your custom view type. Check for spelling mistakes, and don’t assume auto-complete will know. Since Xcode 7, Autocomplete seems to be quite mysterious and doesn’t always work. Anyway, not exactly in scope of this post, as a certain amount of IB experience is assumed.

  1. Pingback: “Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead” – Site Title

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s