Design UITableView's section header in Interface Builder

51,808

Solution 1

I finally solved it using this tutorial, which, largely consists of the following (adapted to my example):

  1. Create SectionHeaderView class that subclasses UIView.
  2. Create SectionHeaderView.xib file and set it's File's Owner's CustomClass to the SectionHeaderView class.
  3. Create an UIView property in the .m file like: @property (strong, nonatomic) IBOutlet UIView *viewContent;
  4. Connect the .xib's View to this viewContent outlet.
  5. Add an initializer method that looks like this:

    + (instancetype)header {
    
        SectionHeaderView *sectionHeaderView = [[SectionHeaderView alloc] init];
    
        if (sectionHeaderView) { // important part
            sectionHeaderView.viewContent = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:sectionHeaderView options:nil] firstObject];
    
            [sectionHeaderView addSubview:sectionHeaderView.viewContent];
    
            return sectionHeaderView;
        }
    
        return nil;
    }
    

Then, I added an UILabel inside the .xib file and connected it to the labelCategoryName outlet and implemented the setCategoryName: method inside the SectionHeaderView class like this:

- (void)setCategoryName:(NSString *)categoryName {

    self.labelCategoryName.text = categoryName;
}

I then implemented the tableView:viewForHeaderInSection: method like this:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    SectionHeaderView *sectionHeaderView = [SectionHeaderView header];

    [sectionHeaderView setCategoryName:self.categoriesNames[section]];

    return sectionHeaderView;
}

And it finally worked. Every section has it's own name, and also UIImageViews show up properly.

Hope it helps others that stumble over the same wrong solutions over and over again, all over the web, like I did.

Solution 2

#Storyboard or XIB. Updated for 2020.

  1. Same Storyboard:

     return tableView.dequeueReusableCell(withIdentifier: "header")
    

    Two Section Headers

  2. Separate XIB (Additional step: you must register that Nib first):

     tableView.register(UINib(nibName: "XIBSectionHeader", bundle:nil),
                        forCellReuseIdentifier: "xibheader")
    

To load from a Storyboard instead of a XIB, see this Stack Overflow answer.


#Using UITableViewCell to create Section Header in IB

Take advantage of the fact that a section header is a regular UIView, and that UITableViewCell is, too, a UIView. In Interface Builder, drag & drop a Table View Cell from the Object Library onto your Table View Prototype Content.

(2020) In modern Xcode, simply increase the "Dynamic Prototypes" number to drop in more cells:

enter image description here

Add an Identifier to the newly added Table View Cell, and customize its appearance to suit your needs. For this example, I used header.

Edit the cell

Use dequeueReusableCell:withIdentifier to locate the cell, just like you would any table view cell.

Don't forget it is just a normal cell: but you are going to use it as a header.

For 2020, simply add to ViewDidLoad the four lines of code:

tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 70   // any reasonable value is fine
tableView.sectionHeaderHeight =  UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 70 // any reasonable value is fine

{See for example this for a discussion.}

Your header cell heights are now completely dynamic. It's fine to change the length of the texts, etc, in the headers.

(TiP: Purely regarding the storyboard: simply select...

enter image description here

...in storyboard, so that the storyboard will work correctly. This has absolutely no effect on the final build. Selecting that checkbox has absolutely no effect whatsoever on the final build. It purely exists to make the storyboard work correctly, if the height is dynamic.)


In older Xcode, or, if for some reason you do not wish to use dynamic heights:

simply supply heightForHeaderInSection, which is hardcoded as 44 for clarity in this example:

//MARK: UITableViewDelegate
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    // This is where you would change section header content
    return tableView.dequeueReusableCell(withIdentifier: "header")
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
    return 44
}

###Swift 2 & earlier:

return tableView.dequeueReusableCellWithIdentifier("header") as? UIView
self.tableView.registerNib(UINib(nibName: "XIBSectionHeader", bundle:nil),
    forCellReuseIdentifier: "xibheader")

► Find this solution on GitHub and additional details on Swift Recipes.

Solution 3

Solution Is way simple

Create one xib, make UI according to your Documentation then in viewForHeaderInSection get xib

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

        NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:self options:nil];

       HeaderView *headerView = [nibArray objectAtIndex:0];

    return headerView;
} 
Share:
51,808
Iulian Onofrei
Author by

Iulian Onofrei

Professional Typo Fixer. iOS Developer at Mondly. Proud member of the fastlane team.

Updated on July 09, 2022

Comments

  • Iulian Onofrei
    Iulian Onofrei almost 2 years

    I have a xib file with a UITableView for which I want to add a custom section header view using the delegate method tableView:viewForHeaderInSection:. Is there any possibility to design it in Interface Builder and then change some of it's subview's properties programmatically?

    My UITableView has more section headers so creating one UIView in Interface Builder and returning it doesn't work, because I'd have to duplicate it, but there isn't any good method of doing it. Archiving and unarchiving it doesn't work for UIImages so UIImageViews would show up blank.

    Also, I don't want to create them programmatically because they are too complex and the resulting code would be hard to read and maintain.

    Edit 1: Here is my tableView:viewForHeaderInSection: method:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
        if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
            return nil;
        }
    
        CGSize headerSize = CGSizeMake(self.view.frame.size.width, 100);
    
        /* wrapper */
    
        UIView *wrapperView = [UIView viewWithSize:headerSize];
    
        wrapperView.backgroundColor = [UIColor colorWithHexString:@"2670ce"];
    
        /* title */
    
        CGPoint titleMargin = CGPointMake(15, 8);
    
        UILabel *titleLabel = [UILabel labelWithText:self.categoriesNames[section] andFrame:CGEasyRectMake(titleMargin, CGSizeMake(headerSize.width - titleMargin.x * 2, 20))];
    
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.font = [UIFont fontWithStyle:FontStyleRegular andSize:14];
    
        [wrapperView addSubview:titleLabel];
    
        /* body wrapper */
    
        CGPoint bodyWrapperMargin = CGPointMake(10, 8);
    
        CGPoint bodyWrapperViewOrigin = CGPointMake(bodyWrapperMargin.x, CGRectGetMaxY(titleLabel.frame) + bodyWrapperMargin.y);
        CGSize bodyWrapperViewSize = CGSizeMake(headerSize.width - bodyWrapperMargin.x * 2, headerSize.height - bodyWrapperViewOrigin.y - bodyWrapperMargin.y);
    
        UIView *bodyWrapperView = [UIView viewWithFrame:CGEasyRectMake(bodyWrapperViewOrigin, bodyWrapperViewSize)];
    
        [wrapperView addSubview:bodyWrapperView];
    
        /* image */
    
        NSInteger imageSize = 56;
        NSString *imageName = [self getCategoryResourceItem:section + 1][@"image"];
    
        UIImageView *imageView = [UIImageView imageViewWithImage:[UIImage imageNamed:imageName] andFrame:CGEasyRectMake(CGPointZero, CGEqualSizeMake(imageSize))];
    
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = imageSize / 2;
    
        [bodyWrapperView addSubview:imageView];
    
        /* labels */
    
        NSInteger labelsWidth = 60;
    
        UILabel *firstLabel = [UILabel labelWithText:@"first" andFrame:CGRectMake(imageSize + bodyWrapperMargin.x, 0, labelsWidth, 16)];
    
        [bodyWrapperView addSubview:firstLabel];
    
        UILabel *secondLabel = [UILabel labelWithText:@"second" andFrame:CGRectMake(imageSize + bodyWrapperMargin.x, 20, labelsWidth, 16)];
    
        [bodyWrapperView addSubview:secondLabel];
    
        UILabel *thirdLabel = [UILabel labelWithText:@"third" andFrame:CGRectMake(imageSize + bodyWrapperMargin.x, 40, labelsWidth, 16)];
    
        [bodyWrapperView addSubview:thirdLabel];
    
        [@[ firstLabel, secondLabel, thirdLabel ] forEachView:^(UIView *view) {
            UILabel *label = (UILabel *)view;
    
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont fontWithStyle:FontStyleLight andSize:11];
        }];
    
        /* line */
    
        UIView *lineView = [UIView viewWithFrame:CGRectMake(imageSize + labelsWidth + bodyWrapperMargin.x * 2, bodyWrapperMargin.y, 1, bodyWrapperView.frame.size.height - bodyWrapperMargin.y * 2)];
    
        lineView.backgroundColor = [UIColor whiteColorWithAlpha:0.2];
    
        [bodyWrapperView addSubview:lineView];
    
        /* progress */
    
        CGPoint progressSliderOrigin = CGPointMake(imageSize + labelsWidth + bodyWrapperMargin.x * 3 + 1, bodyWrapperView.frame.size.height / 2 - 15);
        CGSize progressSliderSize = CGSizeMake(bodyWrapperViewSize.width - bodyWrapperMargin.x - progressSliderOrigin.x, 30);
    
        UISlider *progressSlider = [UISlider viewWithFrame:CGEasyRectMake(progressSliderOrigin, progressSliderSize)];
    
        progressSlider.value = [self getCategoryProgress];
    
        [bodyWrapperView addSubview:progressSlider];
    
        return wrapperView;
    }
    

    and I would want it to look something like this:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
        if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
            return nil;
        }
    
        SectionView *sectionView = ... // get the view that is already designed in the Interface Builder
    
        sectionView.headerText = self.categoriesNames[section];
        sectionView.headerImage = [self getCategoryResourceItem:section + 1][@"image"];
    
        sectionView.firstLabelText = @"first";
        sectionView.secondLabelText = @"second";
        sectionView.thirdLabelText = @"third";
    
        sectionView.progress = [self getCategoryProgress];
    
        return wrapperView;
    }
    

    Edit 2: I'm not using a Storyboard, just .xib files. Also, I don't have an UITableViewController, just an UIViewController in which I added an UITableView.

  • Iulian Onofrei
    Iulian Onofrei over 8 years
    At the second point of your answer, there is a problem. As I stated out in the question: "I'd have to duplicate it, but there isn't any good method of doing it. Archiving and unarchiving doesn't work for UIImages so UIImageViews would show up blank.". Second, working with tags I guess it's not quite a good practice, and I know this from my own experience where I find it hard to maintain a UIViewController from a project I'm working on it that uses tags. Thought it might work, I am curious if there isn't any simpler solution. Also, why is the sectionView surrounded by parens?
  • Michael Dautermann
    Michael Dautermann over 8 years
    I did an update to my answer up there to offer a potentially more useful solution and yeah, I agree that tag properties aren't very friendly to use. I haven't done the "loadNibNamed:" method in my own code in a long time so I'm not certain if IBOutlets would work or not, but give them a try. And the parenths around the return value is just my style, it's not a requirement at all. I'll edit them out.
  • Iulian Onofrei
    Iulian Onofrei over 8 years
    Sorry, I forgot to mention that I don't use a Storyboard, just a .xib file, in which I have a UITableView, not a UITableViewController.
  • Iulian Onofrei
    Iulian Onofrei over 8 years
    Also, if I have an UILabel inside that UITableViewCell, how can I change it's text differently for every section?
  • Iulian Onofrei
    Iulian Onofrei over 8 years
    So, if the section header UITableViewCell is in another XIB file, on which UITableView do I call the method dequeueReusableCellWithIdentifier:?
  • SwiftArchitect
    SwiftArchitect over 8 years
    It is as simple as adding self.tableView.registerNib(UINib(nibName: "XIBSectionHeader", bundle:nil), forCellReuseIdentifier: "xibheader") in UITableViewController -viewDidLoad().
  • Iulian Onofrei
    Iulian Onofrei over 8 years
    1) "All sorts"?! There's just 2 lines of code that does the job. 2) Why is a static + wrong? It's just a wrapper for ... alloc] init], I use it all the time like these custom initializers: [UIView viewWithFrame:], [UIView viewAtPoint:]. 3) What has loading an UITableView from a XIB has to do with my problem? I have a XIB file with and UITableView and other UIViews, not only the table, and now, another XIB for the section header. 3) It's my first bounty, and nowhere was written that I'm not allowed to post a solution before the bounty expires. Why not let them vote mine?
  • Iulian Onofrei
    Iulian Onofrei over 8 years
    I don't have an UITableViewController.
  • Vitalii Gozhenko
    Vitalii Gozhenko over 8 years
    Before use this way, check this answer. Because you will have a problem with layout/touch handling, and reusing of such section views. stackoverflow.com/questions/9219234/…
  • SwiftArchitect
    SwiftArchitect over 8 years
    How is this loadNibNamed solution proposed on Aug 27 any different from the accepted solution?
  • SwiftArchitect
    SwiftArchitect over 8 years
    Clarification: There is no mention of a UITableViewController, only a UITableViewDelegate.
  • Michael Dautermann
    Michael Dautermann over 8 years
    probably because I made this solution first, @SwiftArchitect
  • Iulian Onofrei
    Iulian Onofrei over 8 years
    And how am I supposed to change an UILabel's text from the HeaderView?
  • Joel Teply
    Joel Teply almost 8 years
    I think this has changed now. Use tableView.dequeueReusableCellWithIdentifier("header")?.conte‌​ntView. Casting to UIView will always fail.
  • Frederik Winkelsdorf
    Frederik Winkelsdorf over 7 years
    @SwiftArchitect Any reason for not using the appropriate method? dequeueReusableHeaderFooterView() should be used instead of dequeueReusableCellWithIdentifier.
  • SwiftArchitect
    SwiftArchitect over 7 years
    dequeueReusableHeaderFooterView do not mix well with Storyboard.
  • mfaani
    mfaani over 7 years
    what does "same storyboard" mean?!
  • SwiftArchitect
    SwiftArchitect over 7 years
    The UITableViewCell is defined in the same Storyboard as the UITableViewController.
  • sethfri
    sethfri almost 7 years
    "Not mixing well with storyboard" is a poor excuse for using a completely inappropriate method for your header and footer views. dequeueReusableHeaderFooterView() should definitely be used instead; @FrederikA.Winkelsdorf is correct
  • Aju Antony
    Aju Antony almost 7 years
    Apart from @FrederikA.Winkelsdorf 's suggestion, this answer is spot on, This should be accepted
  • Fattie
    Fattie almost 4 years
    Some of the comments here somewhat confuse the issue that this is the perfect approach in modern iOS, thanks again!
  • SeriousSam
    SeriousSam almost 4 years
    Mate - Apple has such a lovely document covering headerfooter views. You can easily refer that for custom header footer view :) developer.apple.com/documentation/uikit/views_and_controls/…
  • Iulian Onofrei
    Iulian Onofrei almost 4 years
    No, it doesn't. The example on that page is created programatically, which I stated that I don't want.
  • Fattie
    Fattie almost 4 years
    @sethfri - your comment is incorrect: it is not a header or footer - it's a cell. It is perfectly, totally, completely OK to use "table view cells" for other purposes - just for example, for some reason you could just use one "in a screen somewhere". (We do that all the time to match a cell.) In this case you are (correctly) using a cell ... for header use. You would not use dequeueReusableHeaderFooterView ... because it's not a header! it's "just a view". It's completely OK to use a table cell as "just a view" if you need to for some reason, and that's what's happening here.
  • Fattie
    Fattie almost 4 years
    @FrederikA.Winkelsdorf - that method would be quite wrong, it's not a header. It's just a normal cell. It's perfectly normal and OK to use a table cell as "just a view" (for one reason or another) - and that's what's happening here.
  • Frederik Winkelsdorf
    Frederik Winkelsdorf almost 4 years
    @Fattie Well, I don't agree with you when you say "quite wrong". Apple still recommends it: "Always use a UITableViewHeaderFooterView". See the example for viewForHeaderInSection in the Docs on developer.apple.com/documentation/uikit/views_and_controls/…‌​. That said of course it works well to use a Cell as a Header/Footer View without any issues I'm aware of. That's why my reply in 2016 was a question "Any reason for not using the appropriate method?". If you are aware of any reason, feel free to shed some light on this.
  • Fattie
    Fattie almost 4 years
    hi @FrederikA.Winkelsdorf , I really understand what you're saying but. Your comment was on the method used - dequeueReusableCell:withIdentifier. Note that in the approach presented in this answer, the "whole point of the answer" is that you are using a normal cell. So you definitely have to use the method "dequeueReusableCell:withIdentifier". Given that you are using a normal cell you simply must use that call. Indeed no other call will work, end of story.
  • Fattie
    Fattie almost 4 years
    @FrederikA.Winkelsdorf , I really understand, your point may be: "This whole answer is crap! Don't try to use a normal cell as a header!" :) if so, that is a perfectly reasonable viewpoint! But it's confusing to say it is the wrong method. You simply have to use that method when using a cell (for any reason).
  • sethfri
    sethfri almost 4 years
    @Fattie It is incorrect to dequeue a cell from the cell reuse queue when not using it to populate a cell in the table view. You can refer to the docs on this. If you want to use a cell for your header view for whatever reason, just instantiate one directly in tableView(_:viewForHeaderInSection:). If you pull out a cell from the reuse queue and use it as a header, the data source can't mark it for reuse when the user scrolls, so you'll risk exhausting the reuse queue with each header.
  • Frederik Winkelsdorf
    Frederik Winkelsdorf almost 4 years
    @Fattie Agreed, that was probably the part of the misunderstanding. I now got your point, thanks for the clarification. You focussed on me saying "method", where I should've said method and class/implementation that's dequeued. That went hand in hand in my question about not using the "appropriate method". Being more concise is never a bad idea when trying to help others.
  • Fattie
    Fattie almost 4 years
    @FrederikA.Winkelsdorf ahhh, I see what you mean, the "method used", the ":technique" !! :) I particularly thought you literally meant the "method" ie that call :) :) cheers ..
  • Frederik Winkelsdorf
    Frederik Winkelsdorf almost 4 years
    @Fattie Exactly, that was my (language) fault, next time I'll be more specific as this might really cause some confusion (as it did) ^^ :) Cheers
  • MH175
    MH175 almost 3 years
    I tentatively would agree with Frederik Winkelsdorf and caution against this technique because it does not subclass UITableViewHeaderFooterView as Apple says you should. In my current project I get jerky animations when inserting and deleting rows unless it is so. I suspect there are some hidden calculations done behind the scenes for this subclass. Need to investigate further but just a heads up if you run into this issue.