mvasco mvasco - 2 years ago 353
iOS Question

How to change font style and background color in titleForHeaderInSection method

after long reading and checking code, I am proud to have a custom table view with sections and section titles, all populated from core data objects. Now I would need to customize the section title and background color. I have seen it done but in a

method. Is is not possible inside my
Here you have my method:

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections]objectAtIndex:section];
NSString *sectionname = [theSection name];
if ([sectionname isEqualToString:@"text 1"]){
return @"Today";

else if ([sectionname isEqualToString:@"text 2"]){
return @"Tomorrow";

if ([[self.fetchedResultsController sections]count]>0){
id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
return [sectionInfo name];
return nil;


Answer Source

Here's an example that uses your existing code to set the title text, but lets you use UITableViewHeaderFooterView to adjust the appearance:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    static NSString *header = @"customHeader";

    UITableViewHeaderFooterView *vHeader;

    vHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:header];

    if (!vHeader) {
        vHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:header];
        vHeader.textLabel.backgroundColor = [UIColor redColor];

    vHeader.textLabel.text = [self tableView:tableView titleForHeaderInSection:section];

    return vHeader;

If you want, you can even subclass UITableViewHeaderFooterView just like you'd subclass UITableViewCell to customize the appearance even further.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download