Clarence
Clarence

Reputation: 1943

Custom grouped UITable header in different sections

I have a question on multiple sections headers at different sections.

I have the following codes for the first section header text. however, in the second section, it displays the same header text as the first section. May I know how to modify the code so that i can display other text in the second header?

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)];

// create the button object
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.highlightedTextColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:20];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);

// If you want to align the header text as centered
// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);

headerLabel.text = @"section 1"; // i.e. array element
[customView addSubview:headerLabel];

return customView;
}

Upvotes: 0

Views: 396

Answers (2)

Manish Agrawal
Manish Agrawal

Reputation: 11037

you have to use different customView for each section.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section  {
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)];
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.opaque = NO;
    headerLabel.textColor = [UIColor whiteColor];
    headerLabel.highlightedTextColor = [UIColor whiteColor];
    headerLabel.font = [UIFont boldSystemFontOfSize:20];
    headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);

    // If you want to align the header text as centered
    // headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);
if(section == 1)
    headerLabel.text = @"section 1"; // i.e. array element
else if(section == 2)
    headerLabel.text = @"section 2"; // i.e. array element
else
    headerLabel.text = @"section 3";//and so on
    [customView addSubview:headerLabel];

    return customView;
 }

Upvotes: 2

Anil Kothari
Anil Kothari

Reputation: 7733

Instead of this

headerLabel.text = @"section 1"; // i.e. array element

Use this

headerLabel.text=[arrayContainingSectionName objectAtIndex:section];

Upvotes: 2

Related Questions