ChatGPT解决这个技术问题 Extra ChatGPT

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.

I really appreciate the edit RE newer iOS versions.

P
Peter Kreinz

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
}

I had no idea this had even been added to the SDK. Brilliant! Absolutely the correct answer.
OP - Please update the accepted answer to this one. Much cleaner than the old approaches.
This doesn't seem to be working for me. The text color works but not the tint for the header background. I am on iOS 7.0.4
user1639164 ,you can use header.backgroundView.backgroundColor=[UIColor blackColor]; to set the tint for the header background.
@Kent it's been a while obviously, but for future people the header.contentView.backgroundColor = [UIColor blackColor]; option will give you an opaque header
F
FluffyKitten

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.


It can also help to adjust the section header size using self.tableView.sectionHeaderHeight. Otherwise, you may have trouble seeing the text you display for the section title.
Works fine with [UIColor xxxColor] however when I try a custom colour like ones I can get from photoshop (so using the UIColor red:green:blue:alpha:, it is just white. Am I doing something wrong?
Post a separate question and we'll try to help. Include source code.
Note that this answer (while correct) will simply return a UIView with no content.
This is pretty outdated information and simply creating another view isn't the best answer. The idea is to get the proper view and change the color or tint on it. The answer below using willDisplayHeaderView is a much better approach.
p
pkamb

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];

Thanks DoctorG - This was useful. BTW - to keep the existing label provided by the dataSource, I modified the 2nd line like so: label.text = [tableView.dataSource tableView:tableView titleForHeaderInSection:section]; Might be bad form, but it worked for me. Maybe this can help someone else.
@JJ That form is actually fine, since you're calling the same method you'd initially use to define the table's section header.
I removed the autorelease and changed it to an explicit release. UITableView formatting methods are called many, many times. Avoid using autorelease when possible.
@Harkonian, rather than change the submitted answer, please recommend the change in a comment to the answer. It's considered bad form to change other people's code with an edit. Spelling errors, and bad formatting and grammar are fair game.
Instead of addSubview:UILabel, you should just be returning UILabel in viewForHeaderInSection. UILable is-a UIView already :)
D
Denis Kutlubaev

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

hm... it does not work for me. tried iOS 6 simulator and iOS 7 device. Did you tested this way? Where should i place it?
It can be done in application:didFinishLaunchingWithOptions: method of application delegate.
my fault: I tried to use this way while UITableViewStyleGrouped BTW: to change text color this way should be used stackoverflow.com/a/20778406/751932
If it's in custom UIView, just put it in - init method.
Other solution is not worked for me but it was worked.
M
Max

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()

}

A
Alex

Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.


S
Steve

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"

https://i.stack.imgur.com/Q808i.png


w
whyoz

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;
}

This is not needed anymore if you follow the iOS6 and later answer by Dj S.
W
William Jockusch

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;
    }
}

t
theNoobDev10

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 :]


let header = view as! UITableViewHeaderFooterView
R
Roozbeh Zabihollahi

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

N
Nii Mantse

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!


Setting the background color on UITableViewHeaderFooterView has been deprecated. You must set a custom UIView with your desired background color to the backgroundView property instead.
a
animuson

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;
}

C
Corona

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.


A
A.J. Hernandez

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

}

D
David Sanford

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
    }

in iOS 13 replace "view.backgroundColor" to "view.tintColor".
Worked as expected... (0_0) Thanks.!
a
arango_86

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
    }

S
SuryaKantSharma

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
    }

G
Gent

iOS 8+

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}

n
nsinvocation

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
ICL1901

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];

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

m
mmtootmm

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
}

M
Maksymilian Wojakowski

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;
}

R
Ramesh Kumar

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
}

C
Cmar

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
}

P
Pokotuz

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.


I
Idrees Ashraf

In my case, It worked like this:

let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white

L
Lukas Mohs

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     
}

F
Farrukh Makhmudov

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
}

}