Changing Font Size For UITableView Section Headers - ios

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.

Another way to do this would be to respond to the UITableViewDelegate method willDisplayHeaderView. The passed view is actually an instance of a UITableViewHeaderFooterView.
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 this willDisplayHeaderView method.)
You could then respond to the titleForHeaderInSection method to reuse this configured header with different section titles.
Objective-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.textColor = [UIColor redColor];
header.textLabel.font = [UIFont boldSystemFontOfSize:18];
CGRect headerFrame = header.frame;
header.textLabel.frame = headerFrame;
header.textLabel.textAlignment = NSTextAlignmentCenter;
}
Swift 1.2
(Note: if your view controller is a descendant of a UITableViewController, this would need to be declared as override func.)
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
header.textLabel.font = UIFont.boldSystemFontOfSize(18)
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Center
}
Swift 3.0
This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textColor = UIColor.red
header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
header.textLabel?.frame = header.bounds
header.textLabel?.textAlignment = .center
}

Unfortunately, you may have to override this:
In Objective-C:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
In Swift:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
Try something like this:
In Objective-C:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UILabel *myLabel = [[UILabel alloc] init];
myLabel.frame = CGRectMake(20, 8, 320, 20);
myLabel.font = [UIFont boldSystemFontOfSize:18];
myLabel.text = [self tableView:tableView titleForHeaderInSection:section];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
In Swift:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let myLabel = UILabel()
myLabel.frame = CGRect(x: 20, y: 8, width: 320, height: 20)
myLabel.font = UIFont.boldSystemFont(ofSize: 18)
myLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
let headerView = UIView()
headerView.addSubview(myLabel)
return headerView
}

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:
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:28]];
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.

For iOS 7 I use this,
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
header.textLabel.textColor = [UIColor orangeColor];
}
Here is Swift 3.0 version with header resizing
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
header.textLabel!.textColor = UIColor.orange
}
}

Swift 3:
Simplest way to adjust only size:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
if let textlabel = header.textLabel {
textlabel.font = textlabel.font.withSize(15)
}
}

Swift 2.0:
Replace default section header with fully customisable UILabel.
Implement viewForHeaderInSection, like so:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
if sectionTitle == "" {
return nil
}
let title: UILabel = UILabel()
title.text = sectionTitle
title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8)
title.backgroundColor = UIColor.clearColor()
title.font = UIFont.boldSystemFontOfSize(15)
return title
}
Alter the default header (retains default).
Implement willDisplayHeaderView, like so:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView {
view.backgroundView?.backgroundColor = UIColor.blueColor()
view.textLabel!.backgroundColor = UIColor.clearColor()
view.textLabel!.textColor = UIColor.whiteColor()
view.textLabel!.font = UIFont.boldSystemFontOfSize(15)
}
}
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:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30.0 // Or whatever height you want!
}

Here it is, You have to follow write a few methods here. #Swift 5
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as? UITableViewHeaderFooterView
header?.textLabel?.font = UIFont.init(name: "Montserrat-Regular", size: 14)
header?.textLabel?.textColor = .greyishBrown
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 26
}
Have a good luck

With this method you can set font size, font style and Header background also.
there are have 2 method for this
First Method
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.backgroundView.backgroundColor = [UIColor darkGrayColor];
header.textLabel.font=[UIFont fontWithName:#"Open Sans-Regular" size:12];
[header.textLabel setTextColor:[UIColor whiteColor]];
}
Second Method
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
// myLabel.frame = CGRectMake(20, 8, 320, 20);
myLabel.font = [UIFont fontWithName:#"Open Sans-Regular" size:12];
myLabel.text = [NSString stringWithFormat:#" %#",[self tableView:FilterSearchTable titleForHeaderInSection:section]];
myLabel.backgroundColor=[UIColor blueColor];
myLabel.textColor=[UIColor whiteColor];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}

Swift 4 version of Leo Natan answer is
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)
If you wanted to set a custom font you could use
if let font = UIFont(name: "font-name", size: 12) {
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}

Swift 2:
As OP asked, only adjust the size, not setting it as a system bold font or whatever:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel {
let newSize = CGFloat(16)
let fontName = textLabel.font.fontName
textLabel.font = UIFont(name: fontName, size: newSize)
}
}

This is my solution with swift 5.
To fully control the header section view, you need to use the tableView(:viewForHeaderInsection::) method in your controller, as the previous post showed. However, there is a further step: to improve performance, apple recommend not generate a new view every time but to re-use the header view, just like reuse table cell. This is by method tableView.dequeueReusableHeaderFooterView(withIdentifier: ). But the problem I had is once you start to use this re-use function, the font won't function as expected. Other things like color, alignment all fine but just font. There are some discussions but I made it work like the following.
The problem is tableView.dequeueReusableHeaderFooterView(withIdentifier:) is not like tableView.dequeneReuseCell(:) which always returns a cell. The former will return a nil if no one available. Even if it returns a reuse header view, it is not your original class type, but a UITableHeaderFooterView. So you need to do the judgement and act according in your own code. Basically, if it is nil, get a brand new header view. If not nil, force to cast so you can control.
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let reuse_header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "yourHeaderID")
if (reuse_header == nil) {
let new_sec_header = YourTableHeaderViewClass(reuseIdentifier:"yourHeaderID")
new_section_header.label.text="yourHeaderString"
//do whatever to set color. alignment, etc to the label view property
//note: the label property here should be your custom label view. Not the build-in labelView. This way you have total control.
return new_section_header
}
else {
let new_section_header = reuse_section_header as! yourTableHeaderViewClass
new_sec_header.label.text="yourHeaderString"
//do whatever color, alignment, etc to the label property
return new_sec_header}
}

Related

Swift: Changing TableView Header text color - Crashing

Using Swift 3, I'm trying to change the Section's Header color programmatically.
How do I change the backgroundColor to white and Text Color to black?
The sections header changes color but no text appears and then when I add code to change the header text color it crashes
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Can't add self as subview'
Swift Code
// Title for Header
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// Section Names
let sectionNames = ["Followed Blogs", "All Blogs"]
return sectionNames[section]
}
// View for Header
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerLabel = UILabel()
let sectionNames = ["Followed Blogs", "All Blogs"]
headerLabel.text = sectionNames[section]
headerLabel.frame = CGRect(x: 45, y: 5, width: 100, height: 35)
headerLabel.addSubview(headerLabel)
if (section == 0) {
headerView.backgroundColor = UIColor.green
headerLabel.textColor = UIColor.black
} else {
if darkMode {
headerView.backgroundColor = UIColor.white
headerLabel.textColor = UIColor.black
} else {
headerView.backgroundColor = UIColor.black
headerLabel.textColor = UIColor.white
}
}
return headerView
}
// Height for Section
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
headerLabel.addSubview(headerLabel) is adding the label to self, which is the source of your error
Based on my understanding of your code, you should probably be using headerView.addSubview(headerLabel) instead
The text "Followed Blogs" doesn't fit it shows as "Followed B..."
This is (most likely) a layout issue, I'd personally investigate adding auto layout constraints to the label so that it binds to the top/bottom/left/right margins of the parent view
This is just to add on MadProgrammer's answer. I think instead of UIView you should use UITableViewHeaderFooterView
usage:
tableViewInstance.register(UITableViewHeaderFooterView.self, forHeaderFooterViewResuseIdentifier: "headerIdentifier")
Then in viewForHeaderInSection:
let tableViewHeader = tableview.dequeueReusableHeaderFooterView(withIdentifier: "headerIdentifier")
btw, regarding the text "Followed Blogs" not fitting in its because of your label's width is too small for the current font. Why not add a constraints like this:
headerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[label]-5-|",
options: [],
metrics: nil,
views: ["tableView": headerLabel]))
headerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[label]-5-|",
options: [],
metrics: nil,
views: ["tableView": headerLabel]))
You make your tableView's headerHeight be dynamic

UITableViewCell won't not receiving touches

I am implementing a view that displays a lot of information. The view is scrollable and inside of the view I implemented a non-scrollable table view holding user comments. I have all the auto-layout constraints and it appears to layout correctly however touches are not received below a certain row. It appears that the table view or something is blocking the views below from receiving the events but I am unable to trace down the issue.
I want the main scroll view's content size to grow as the comment table view grows. Keeping the post comment view at the bottom of the table view. Right now I can't select the last cell or the text field.
Comment Cell View
Simulator screenshot
Here is the code from the table view implementation:
commentsTableView.delegate = self
commentsTableView.dataSource = self
commentsTableView.estimatedRowHeight = 82
commentsTableView.rowHeight = UITableViewAutomaticDimension
commentsTableView.sectionHeaderHeight = UITableViewAutomaticDimension
commentsTableView.estimatedSectionHeaderHeight = 54
commentsTableView.estimatedSectionFooterHeight = 0
commentsTableView.sectionHeaderHeight = UITableViewAutomaticDimension
commentsTableView.tableFooterView = UIView(frame: CGRectZero)
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Comments"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section != 0 { return nil }
let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
if sectionTitle == "" {
return nil
}
let view = UIView(frame: CGRectMake(0, 0, tableView.frame.width, 54))
let title = UILabel(frame: CGRectMake(60, 22, tableView.frame.width, 17))
view.addSubview(title)
title.text = sectionTitle
title.textColor = UIColor(red: (74 / 255), green: (74 / 255), blue: (74 / 255), alpha: 1.0)
title.backgroundColor = UIColor.clearColor()
view.backgroundColor = UIColor.clearColor()
title.font = UIFont(name: "ProximaNova-Semibold", size: 16.0)
view.layer.addBorder(.Bottom, color: UIColor.lightGrayColor().colorWithAlphaComponent(0.75), thickness: 0.5)
title.setNeedsDisplay()
view.setNeedsDisplay()
return view
}
You have to set the userInteractionEnabled to true to fire those events.
view.userInteractionEnabled = true
The Comment TextField is the last row of your comment TableView. So put comment TextField code in footer of the TableView as follows:
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let commentTextFieldView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 50))
// Your Comment TextField code
return commentTextFieldView
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 50.0
}
There is an another way to assign Comment TextField view as tableView footer:
myTableView.tableFooterView = commentTextFieldView

TableView Header/Footer Font in Grouped Table (Swift)

I changed a tableView from Plain to Grouped so that the header/footer does not float over the table and stays anchored to the top and bottom of the table. That was straightforward, but now the font style formatting that I setup is not working. Strangely all other formatting of the header/footer seems to be working though. Any thoughts on what is going and what I am missing are appreciated!
Code below:
// Setup format of the header
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let title = UILabel()
title.font = UIFont(name: "Avenir Book", size: 12)
title.textColor = UIColor.whiteColor()
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = UIColor(red: 30/255, green: 30/255, blue: 50/255, alpha: 1)
header.textLabel!.font = title.font
header.textLabel?.textColor = title.textColor
header.textLabel?.numberOfLines = 0
header.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
header.textLabel?.textAlignment = NSTextAlignment.Center
}
In a Plain table all of the above works great and looks like this:
However, when I change to Grouped table all of the formatting seems to show up except for the font style this this:
I am puzzled about where the ALL CAPS is coming from.
I tried to implement the solution from this question/answer, but could not get it to work either. Thanks for your ideas!
Assuming that you provided the string for the section title in this method:
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
But in a grouped tableview, that string is changed to all caps. To remove the all caps, try adding one of these two lines in the willDisplayHeaderView method:
header.textLabel?.text = header.textLabel!.text!.capitalizedString
header.textLabel?.text = header.textLabel!.text!.lowercaseString
The first one will capitalize the first letter of every word and the second will make everything lowercase. If you don't want either of those you could add the string directly:
header.textLabel?.text = "Here are a few options for you. Select to learn more"
Swift 4
use this delegates:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label: UILabel = {
let label = UILabel()
label.textAlignment = .right
label.textColor = .white
label.backgroundColor = .clear
label.font = UIFont.systemFont(ofSize: 20)
return label
}()
return label
}
and don't forget to set height for header:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 70
}
hope this help.
Update for >=iOS 14, with the UIListContentConfiguration API:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let headerView = view as? UITableViewHeaderFooterView else {
return
}
var config = headerView.defaultContentConfiguration()
// This needs to explicitly be set if the table view is Grouped style
// (which it is, to hide sticky backgrounds on section headers),
// as the deafult style for
config.textProperties.transform = .none
// Other properties (color, font) as needed...
// Notably, `ContentConfiguration` requires setting content here as well,
// separate from `titleForHeaderInSection`
config.text = "MyText"
headerView.contentConfiguration = config
headerView.setNeedsUpdateConfiguration()
}

How to customise header section in static cell?

I want to customise the header section in my application but it's in static cell. I tried to make one cell to be my header by including identifier and add a new file to control that cell but that doesn't work. I tried to drag an object into new file but it's can't be done. So how to customise section header? Is my way of approach is good?
There are a couple of ways to customize the header section in a UITableView. For instance, if all you want to do is change the text, you can do so in the attributes inspector while making sure your TableViewSection is selected:
However, if you want the ability to do customizations such as text size, tont, capitalizations - any customizations inherent to UILabels, you'll need to override this method from the UITableViewController:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor(red: 243/255, green: 153/255, blue: 193/255, alpha: 1.0)
header.textLabel.font = UIFont(name: "Helvetica Neue", size: 18)
header.textLabel.text = "About Us"
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Left
}
For example, in the code above, I took the header that was passed as a parameter and configured the textColor, font, text, alignment - really anything you can do on the UILabel can be done here.
Before customization
After customization
Also you can customise header section use Nib. Simple example below.
HeaderView.xib (Screenshot)
HeaderView.swift
import UIKit
class HeaderView: UITableViewHeaderFooterView {
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var titleBackgroundView: UIView!
static var nib: UINib {
return UINib(nibName: identifier, bundle: nil)
}
static var identifier: String {
return String(describing: self)
}
override func awakeFromNib() {
titleBackgroundView.layer.shadowColor = UIColor.gray.cgColor
titleBackgroundView.layer.shadowOpacity = 0.5
titleBackgroundView.layer.shadowOffset = CGSize(width: 0, height: 5)
titleBackgroundView.layer.shadowRadius = 5
}
}
ProfileTableViewController.swift
import UIKit
class ProfileTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(HeaderView.nib, forHeaderFooterViewReuseIdentifier: HeaderView.identifier)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderView.identifier) as! HeaderView
switch section {
case 0:
headerView.titleLabel.text = "Profile"
return headerView
case 1:
headerView.titleLabel.text = "Social"
return headerView
default:
return UIView()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
}
Simulator (Screenshot)
This is the easy way to do it without set a new string, just leave text in header that used in UITableview with static cell as it and add this override for header in your code
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
((UITableViewHeaderFooterView*)view).textLabel.text = [((UITableViewHeaderFooterView*)view).textLabel.text capitalizedString];
}
}

UITableView - change section header color

How can I change color of a section header in UITableView?
EDIT: The answer provided by DJ-S should be considered for iOS 6 and above. The accepted answer is out of date.
This is an old question, but I think the answer needs to be updated.
This method does not involve defining and creating your own custom view.
In iOS 6 and up, you can easily change the background color and the text color by defining the
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
section delegate method
For example:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor blackColor];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// header.contentView.backgroundColor = [UIColor blackColor];
}
Taken from my post here:
https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/
Swift 3 / 4
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.red
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.white
}
Hopefully this method from the UITableViewDelegate protocol will get you started:
Objective-C:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
if (section == integerRepresentingYourSectionOfInterest)
[headerView setBackgroundColor:[UIColor redColor]];
else
[headerView setBackgroundColor:[UIColor clearColor]];
return headerView;
}
Swift:
func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.redColor()
} else {
headerView.backgroundColor = UIColor.clearColor()
}
return headerView
}
Updated 2017:
Swift 3:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.red
} else {
headerView.backgroundColor = UIColor.clear
}
return headerView
}
Replace [UIColor redColor] with whichever UIColor you would like. You may also wish to adjust the dimensions of headerView.
Here's how to change the text color.
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = #"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];
You can do this if you want header with custom color. This solution works great since iOS 6.0.
Objective C:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
Swift:
UITableViewHeaderFooterView.appearance().tintColor = .white
The following solution works for Swift 1.2 with iOS 8+
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This changes the header background
view.tintColor = UIColor.blueColor()
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel.textColor = UIColor.redColor()
}
Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
You can do it on main.storyboard in about 2 seconds.
Select Table View
Go to Attributes Inspector
List item
Scroll down to View subheading
Change "background"
Don't forget to add this piece of code from the delegate or your view will be cut off or appear behind the table in some cases, relative to the height of your view/label.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
If you don't want to create a custom view, you can also change the color like this (requires iOS 6):
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
UIView* content = castView.contentView;
UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here
content.backgroundColor = color;
}
}
For swift 5 +
In willDisplayHeaderView Method
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//For Header Background Color
view.tintColor = .black
// For Header Text Color
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = .white
}
I hope this helps you :]
Set the background and text color of section area: (Thanks to William Jockusch and Dj S)
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
castView.contentView.backgroundColor = [UIColor grayColor];
[castView.textLabel setTextColor:[UIColor grayColor]];
}
}
Swift 4
To change the background color, text label color and font for the Header View of a UITableView Section, simply override willDisplayHeaderView for your table view like so:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.backgroundView?.backgroundColor = .white
header.textLabel?.textColor = .black
header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
}
This worked perfectly for me; hope it does help you too!
Here's how to add an image in header view:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"top-gery-bar.png"]] autorelease];
headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);
[headerView addSubview:headerImage];
return headerView;
}
For iOS8 (Beta) and Swift choose the RGB Color you want and try this:
override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView()
header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1)
return header
}
(The "override" is there since i´m using the UITableViewController instead of a normal UIViewController in my project, but it´s not mandatory for changing the section header color)
The text of your header will still be seen.
Note that you will need to adjust the section header height.
Good Luck.
SWIFT 2
I was able to successfully change the section background color with an added blur effect (which is really cool). To change the background color of section easily:
First go to Storyboard and select the Table View
Go to Attributes Inspector
List item
Scroll down to View
Change "Background"
Then for blur effect, add to code:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This is the blur effect
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.darkGrayColor()
headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
headerView.tintColor = .groupTableViewBackgroundColor()
headerView.backgroundView = blurEffectView
}
Swift 4 makes it very easy. Simply add this to your class and set the color as needed.
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
or if a simple color
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}
Updated for Swift 5
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
or if a simple color
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.white
}
For me none of above works after wasting 2 hours what this is the solution. In my case it was custom view but I cannot able to change it from storyboard and view's awakeFromNib for some reason.
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = .white
}
I know its answered, just in case, In Swift use the following
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let tableViewWidth = self.tableView.bounds
let headerView = UIView(frame: CGRectMake(0, 0, tableViewWidth.size.width, self.tableView.sectionHeaderHeight))
headerView.backgroundColor = UIColor.greenColor()
return headerView
}
iOS 8+
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
Based on #Dj S answer, using Swift 3. This works great on iOS 10.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
I have a project using static table view cells, in iOS 7.x. willDisplayHeaderView does not fire. However, this method works ok:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSLog(#"%s", __FUNCTION__);
CGRect headerFrame = CGRectMake(x, y, w, h);
UIView *headerView = [[UIView alloc] initWithFrame:headerFrame];
headerView.backgroundColor = [UIColor blackColor];
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]])
{
UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view;
UIView *content = castView.contentView;
UIColor *color = [UIColor whiteColor]; // substitute your color here
content.backgroundColor = color;
[castView.textLabel setTextColor:[UIColor blackColor]];
}
}
I think this code is not so bad.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.whiteColor()
headerView.backgroundView = backgroundView
headerView.textLabel.text = "hello"
return headerView
}
In iOS 7.0.4 I created a custom header with it's own XIB. Nothing mentioned here before worked. It had to be the subclass of the UITableViewHeaderFooterView to work with the dequeueReusableHeaderFooterViewWithIdentifier: and it seems that class is very stubborn regarding the background color. So finally I added an UIView (you could do it either with code or IB) with name customBackgroudView, and then set it's backgroundColor property. In layoutSubviews: I set that view's frame to bounds. It work with iOS 7 and gives no glitches.
// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
// first child becomes contentView
// in MyTableHeaderView.h
#property (nonatomic, weak) IBOutlet UIView * customBackgroundView;
// in MyTableHeaderView.m
-(void)layoutSubviews;
{
[super layoutSubviews];
self.customBackgroundView.frame = self.bounds;
}
// if you don't have XIB / use IB, put in the initializer:
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
...
UIView * customBackgroundView = [[UIView alloc] init];
[self.contentView addSubview:customBackgroundView];
_customBackgroundView = customBackgroundView;
...
}
// in MyTableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
MyTableHeaderView * header = [self.tableView
dequeueReusableHeaderFooterViewWithIdentifier:#"MyTableHeaderView"];
header.customBackgroundView.backgroundColor = [UIColor redColor];
return header;
}
Just change the color of layer of the header view
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
headerView.layer.backgroundColor = [UIColor clearColor].CGColor
}
If anyone needs swift, keeps title:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
view.backgroundColor = UIColor.redColor()
let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
label.text = self.tableView(tableView, titleForHeaderInSection: section)
view.addSubview(label)
return view
}
I got message from Xcode through console log
[TableView] Setting the background color on
UITableViewHeaderFooterView has been deprecated. Please set a custom
UIView with your desired background color to the backgroundView
property instead.
Then I just create a new UIView and lay it as background of HeaderView.
Not a good solution but it easy as Xcode said.
In my case, It worked like this:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
Just set the background color of the background view:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
If you are using a custom header view:
class YourCustomHeaderFooterView: UITableViewHeaderFooterView {
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.backgroundColor = .white //Or any color you want
}
}

Resources