user3654554
user3654554

Reputation: 17

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

Upvotes: 1

Views: 2756

Answers (3)

Tiago Mendes
Tiago Mendes

Reputation: 5156

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {

    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    header.textLabel.textColor = [UIColor redColor];
    CGRect headerFrame = header.frame;
    header.textLabel.frame = headerFrame;
    [header.contentView setBackgroundColor:[UIColor blueColor]];
}

Upvotes: 0

Schuuure
Schuuure

Reputation: 301

If you are simply looking to change the background and font color s of a header view, a simpler approach may be to just use

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

There is a very nice example/explanation here.

Upvotes: 3

nprd
nprd

Reputation: 1942

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;

}

Upvotes: 0

Related Questions