ios – 如何在titleForHeaderInSection方法中更改字体样式和背景颜色

经过漫长的阅读和检查代码,我很自豪拥有一个自定义表视图,其中包含部分和部分标题,全部由核心数据对象填充.现在我需要自定义部分标题和背景颜色.我已经看到它完成,但在一个viewForHeaderInSection方法.我的titleForHeaderInSection方法是不可能的吗?
这里有我的方法:
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{




    id <NSFetchedResultsSectionInfo> theSection = [[self.fetchedResultsController sections]objectAtIndex:section];
    NSString *sectionname = [theSection name];
    if ([sectionname isEqualToString:@"text 1"]){
        return @"Today";

    }
    else if ([sectionname isEqualToString:@"text 2"]){
        return @"Tomorrow";
    }


    if ([[self.fetchedResultsController sections]count]>0){
        id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]objectAtIndex:section];
        return [sectionInfo name];
    }
    else{
        return nil;
    }

}

解决方法

以下是使用现有代码设置标题文本的示例,但可以使用UITableViewHeaderFooterView调整外观:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *header = @"customHeader";

    UITableViewHeaderFooterView *vHeader;

    vHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:header];

    if (!vHeader) {
        vHeader = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:header];
        vHeader.textLabel.backgroundColor = [UIColor redColor];
    }

    vHeader.textLabel.text = [self tableView:tableView titleForHeaderInSection:section];

    return vHeader;
}

如果需要,您甚至可以将UITableViewHeaderFooterView子类化,就像您将UITableViewCell子类化以进一步自定义外观.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...