设置UITableView Section Header的颜色

时间:2014-05-19 23:59:38

标签: objective-c xcode uitableview uicolor

如何将我所有部分的节头设置为redColor,而不将它们设置为具有相同的标题字符串,并设置字体和字体颜色。

我尝试了这个,但它摆脱了我的节标题

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

我非常感谢一些示例代码。

提前致谢

3 个答案:

答案 0 :(得分:3)

如果您只是想更改标题视图的背景和字体颜色,更简单的方法可能就是使用

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

有一个非常好的例子/解释here

答案 1 :(得分:0)

尝试自定义节标题视图。您可以扩展此方法。

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

}

答案 2 :(得分:0)

- (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]];
}
相关问题