Can someone please instruct me on the easiest way to change the font size for the text in a UITableView section header?
I have the section titles implemented using the following method:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
Then, I understand how to successfully change the section header height using this method:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
I have the UITableView cells populated using this method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
However, I'm stuck as to how to actually increase the font size - or for that matter the font style - of the section header text?
Can someone please assist? Thanks.
Unfortunately, you may have to override this:
Try something like this:
Swift 2:
As OP asked, only adjust the size, not setting it as a system bold font or whatever:
While mosca1337's answer is a correct solution, be careful with that method. For a header with text longer than one line, you will have to perform the calculations of the height of the header in
tableView:heightForHeaderInSection:
which can be cumbersome.A much preferred method is to use the appearance API:
This will change the font, while still leaving the table to manage the heights itself.
For optimal results, subclass the table view, and add it to the containment chain (in
appearanceWhenContainedIn:
) to make sure the font is only changed for the specific table views.Swift 3:
Simplest way to adjust only size:
Another way to do this would be to respond to the
UITableViewDelegate
methodwillDisplayHeaderView
. The passed view is actually an instance of aUITableViewHeaderFooterView
.The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to
heightForHeaderInSection
to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in thiswillDisplayHeaderView
method.)You could then respond to the
titleForHeaderInSection
method to reuse this configured header with different section titles.Objective-C
Swift 1.2
(Note: if your view controller is a descendant of a
UITableViewController
, this would need to be declared asoverride func
.)Swift 3.0
This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:
Swift 2.0:
Implement viewForHeaderInSection, like so:
Implement willDisplayHeaderView, like so:
Remember: If you're using static cells, the first section header is padded higher than other section headers due to the top of the UITableView; to fix this:
Implement heightForHeaderInSection, like so: