Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 viewForHeaderInSection method. Is is not possible inside my titleForHeaderInSection method? 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];
    }
    else{
        return nil;
    }

}
like image 363
mvasco Avatar asked Jan 14 '14 21:01

mvasco


2 Answers

simple and optimized

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = [UIColor whiteColor];//[UIColor colorWithRed:77.0/255.0 green:162.0/255.0 blue:217.0/255.0 alpha:1.0];
    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tableSection"]]];

}
like image 128
codercat Avatar answered Oct 06 '22 01:10

codercat


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.

like image 23
Aaron Brager Avatar answered Oct 06 '22 01:10

Aaron Brager