UITableView 部分标题不显示自定义图像背景

Posted

技术标签:

【中文标题】UITableView 部分标题不显示自定义图像背景【英文标题】:UITableView SectionHeader not displaying custom image background 【发布时间】:2011-08-14 12:04:51 【问题描述】:

我正在修改TableView 的部分标题的外观。我已经设法让文本工作得很好。但是背景图像似乎根本没有出现。

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 

    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)] autorelease];
    UILabel *sectionTitle = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, 320, 30)] autorelease];
    sectionTitle.text = [[tableDataSource objectAtIndex: section] objectForKey: @"Title"];
    sectionTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
    //sectionTitle.textColor = [UIColor whiteColor];
    sectionTitle.shadowColor = [UIColor colorWithWhite:0 alpha:0.4];
    sectionTitle.shadowOffset = CGSizeMake(1, 1);
    sectionTitle.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    //headerView.backgroundColor = [UIColor whiteColor];

    UIImageView *sectionHeaderBG = [[UIImageView alloc] init];
    UIImage *image = [UIImage imageNamed:@"CellBackgroundGrey4.png"];
    sectionHeaderBG.image = image;

    [headerView addSubview:sectionTitle];    
    [headerView addSubview:sectionHeaderBG];
    [headerView autorelease];
    return headerView;

我有什么遗漏吗?

【问题讨论】:

【参考方案1】:

试一试:

headerView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"CellBackgroundGrey4.png"]]; 

【讨论】:

【参考方案2】:

我认为您错过了设置UIImageViewframe

【讨论】:

【参考方案3】:
//custom sections
- (NSString *)tableView:(UITableView *)tblView titleForHeaderInSection:(NSInteger)section 

    NSString *sectionName = nil;

    //set the table background to clear so you can see the background view behind it
    tableView.backgroundColor = [UIColor clearColor];

    //where does this go?

    UILabel *sectionHeader = [[UILabel alloc] init];
    sectionHeader.backgroundColor = [UIColor clearColor];
    sectionHeader.font = [UIFont boldSystemFontOfSize:18];
    sectionHeader.textColor = [UIColor whiteColor];

    //What is missing here?

    switch (section) 
        case 0:
            sectionName = [NSString stringWithFormat:@"Header Text 1"];
            break;
        case 1:
            sectionName = [NSString stringWithFormat:@"Header Text 2"];
            break;
        case 2:
            sectionName = [NSString stringWithFormat:@"Header Text 3"];
            break;
    

    return sectionName;

【讨论】:

以上是关于UITableView 部分标题不显示自定义图像背景的主要内容,如果未能解决你的问题,请参考以下文章

UITableView detailTextLabel 不适用于自定义单元格

UITableView 错误的图像加载了自定义单元格和 UIView

图像会自动添加到 UItableView Cell 中吗?

自定义 UITableView 单元格图像转换未应用于可重用单元格

UITableView 中的自定义单元格使图像在滚动时重叠

分组 UITableView 上的自定义背景图像