Design UITableView's section header in Interface Builder
Solution 1
I finally solved it using this tutorial, which, largely consists of the following (adapted to my example):
- Create
SectionHeaderView
class that subclassesUIView
. - Create
SectionHeaderView.xib
file and set it'sFile's Owner
'sCustomClass
to theSectionHeaderView
class. - Create an
UIView
property in the.m
file like:@property (strong, nonatomic) IBOutlet UIView *viewContent;
- Connect the
.xib
'sView
to thisviewContent
outlet. -
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 UIImageView
s 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.
-
Same
Storyboard
:return tableView.dequeueReusableCell(withIdentifier: "header")
-
Separate
XIB
(Additional step: you must register thatNib
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:
Add an Identifier to the newly added Table View Cell, and customize its appearance to suit your needs. For this example, I used header
.
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...
...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;
}
Iulian Onofrei
Professional Typo Fixer. iOS Developer at Mondly. Proud member of the fastlane team.
Updated on July 09, 2022Comments
-
Iulian Onofrei almost 2 years
I have a
xib
file with aUITableView
for which I want to add a custom section header view using the delegate methodtableView:viewForHeaderInSection:
. Is there any possibility to design it inInterface Builder
and then change some of it's subview's properties programmatically?My
UITableView
has more section headers so creating oneUIView
inInterface 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 forUIImage
s soUIImageView
s 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 anUITableViewController
, just anUIViewController
in which I added anUITableView
. -
Iulian Onofrei over 8 yearsAt 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
UIImage
s soUIImageView
s 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 aUIViewController
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 thesectionView
surrounded by parens? -
Michael Dautermann over 8 yearsI 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 ifIBOutlets
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 over 8 yearsSorry, I forgot to mention that I don't use a
Storyboard
, just a.xib
file, in which I have aUITableView
, not aUITableViewController
. -
Iulian Onofrei over 8 yearsAlso, if I have an
UILabel
inside thatUITableViewCell
, how can I change it's text differently for every section? -
Iulian Onofrei over 8 yearsSo, if the section header
UITableViewCell
is in anotherXIB
file, on whichUITableView
do I call the methoddequeueReusableCellWithIdentifier:
? -
SwiftArchitect over 8 yearsIt is as simple as adding
self.tableView.registerNib(UINib(nibName: "XIBSectionHeader", bundle:nil), forCellReuseIdentifier: "xibheader")
inUITableViewController -viewDidLoad()
. -
Iulian Onofrei over 8 years1) "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 anUITableView
from aXIB
has to do with my problem? I have aXIB
file with andUITableView
and otherUIView
s, not only the table, and now, anotherXIB
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 over 8 yearsI don't have an
UITableViewController
. -
Vitalii Gozhenko over 8 yearsBefore 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 over 8 yearsHow is this
loadNibNamed
solution proposed on Aug 27 any different from the accepted solution? -
SwiftArchitect over 8 yearsClarification: There is no mention of a
UITableViewController
, only aUITableViewDelegate
. -
Michael Dautermann over 8 yearsprobably because I made this solution first, @SwiftArchitect
-
Iulian Onofrei over 8 yearsAnd how am I supposed to change an
UILabel
's text from theHeaderView
? -
Joel Teply almost 8 yearsI think this has changed now. Use tableView.dequeueReusableCellWithIdentifier("header")?.contentView. Casting to UIView will always fail.
-
Frederik Winkelsdorf over 7 years@SwiftArchitect Any reason for not using the appropriate method?
dequeueReusableHeaderFooterView()
should be used instead ofdequeueReusableCellWithIdentifier
. -
SwiftArchitect over 7 years
dequeueReusableHeaderFooterView
do not mix well with Storyboard. -
mfaani over 7 yearswhat does "same storyboard" mean?!
-
SwiftArchitect over 7 yearsThe
UITableViewCell
is defined in the same Storyboard as theUITableViewController
. -
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 almost 7 yearsApart from @FrederikA.Winkelsdorf 's suggestion, this answer is spot on, This should be accepted
-
Fattie almost 4 yearsSome of the comments here somewhat confuse the issue that this is the perfect approach in modern iOS, thanks again!
-
SeriousSam almost 4 yearsMate - 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 almost 4 yearsNo, it doesn't. The example on that page is created programatically, which I stated that I don't want.
-
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 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 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 almost 4 yearshi @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 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 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 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 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 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 almost 3 yearsI 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.