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

mva*_*sco 15 uitableview ios

经过长时间的阅读和检查代码,我很自豪有一个自定义表视图,其中包含部分和部分标题,所有部分都来自核心数据对象.现在我需要自定义部分标题和背景颜色.我已经看到它已经完成但是在一种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;
    }

}
Run Code Online (Sandbox Code Playgroud)

cod*_*cat 24

简单和优化

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = [UIColor whiteColor];//[UIColor colorWithRed:77.0/255.0 green:162.0/255.0 blue:217.0/255.0 alpha:1.0];
    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tableSection"]]];

}
Run Code Online (Sandbox Code Playgroud)

  • 聪明,但值得注意的是,这可能会在将来的iOS版本中崩溃,因为API无法保证“ view”是UITableViewHeaderFooterView。可能要使用条件转换更安全。 (2认同)

Aar*_*ger 11

这是一个使用现有代码设置标题文本的示例,但允许您使用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;
}
Run Code Online (Sandbox Code Playgroud)

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


cdf*_*982 9

快速实现@ codercat的答案:

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    view.tintColor = UIColor(red: 0.967, green: 0.985, blue: 0.998, alpha: 1) // this example is a light blue, but of course it also works with UIColor.lightGrayColor()

    var header : UITableViewHeaderFooterView = view as UITableViewHeaderFooterView
    header.textLabel.textColor = UIColor.redColor()

}
Run Code Online (Sandbox Code Playgroud)