自定义分组UITable标头在不同的部分

时间:2012-03-07 07:27:06

标签: iphone ios uitableview

我对不同部分的多个部分标题有疑问。

我有第一部分标题文本的以下代码。但是,在第二部分中,它显示与第一部分相同的标题文本。我可以知道如何修改代码,以便我可以在第二个标题中显示其他文本吗?

- (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;
}

2 个答案:

答案 0 :(得分:2)

您必须为每个部分使用不同的customView。

- (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;
 }

答案 1 :(得分:2)

而不是这个

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

使用此

headerLabel.text=[arrayContainingSectionName objectAtIndex:section];
相关问题