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
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
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()
}
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];
}
}
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
}
}