Search code examples
objective-cxcodeuitableviewuicolor

Set color of UITableView Section Header


How can I set the section header of all my section to redColor, without setting them to have all the same header string, and set the font and font color.

I tried this but it gets rid of my section headers

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    if (section == 1)
        [headerView setBackgroundColor:[UIColor redColor]];
    else
        [headerView setBackgroundColor:[UIColor clearColor]];
    return headerView;
}

I would really appreciate some sample code.

thanks in advance


Solution

  • Try customizing your section header view. You can extend this approach.

    - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    
        //Put your common code here
        // lets say you need all background color to be white. do this here
         [headerView setBackgroundColor:[UIColor redColor]];
    
        //Check the section and do section specific contents
        if (section == 1)
            [headerView setText:@"Section 1"];
        else
            [headerView setBackgroundColor:[UIColor clearColor]];
    
      return headerView;
    

    }