如何在分组类型UITableView中更改标题的字体颜色?

Con*_*sed 42 iphone fonts uitableview ios

我有一个分组类型的tableview,它看起来很酷.

但是,如果我将表格的背景颜色更改为黑色,则标题会变得不清楚.

是否可以更改字体颜色及其样式?这样我就可以使它更具可读性.我应该实施这个tableView:viewForHeaderInSection:方法吗?

Adr*_*cas 43

要使用TableView中的默认坐标和部分,请使用白色字体和阴影:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }

    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(20, 8, 320, 20);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.shadowColor = [UIColor grayColor];
    label.shadowOffset = CGSizeMake(-1.0, 1.0);
    label.font = [UIFont boldSystemFontOfSize:16];
    label.text = sectionTitle;

    UIView *view = [[UIView alloc] init];
    [view addSubview:label];

    return view;
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*der 43

如果您只需要更改标题上的颜色或字体,请使用tableView: willDisplayHeaderView: forSection:.这是swift中的一个例子:

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

    if let view = view as? UITableViewHeaderFooterView {
        view.backgroundView?.backgroundColor = UIColor.blue
        view.textLabel?.backgroundColor = UIColor.clear
        view.textLabel?.textColor = UIColor.white
    }
}
Run Code Online (Sandbox Code Playgroud)


Con*_*sed 22

是的......它现在很棒!

我创建了tableView:viewForHeaderInSection:方法并创建了一个UIView

UIView *customTitleView = [ [UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个UILabel并将文本值和颜色设置为标签.然后我将标签添加到视图中

UILabel *titleLabel = [ [UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
titleLabel.text = @"<Title string here>";
titleLabel.textColor = [UIColor whiteColor];
titleLabel.backgroundColor = [UIColor clearColor];
[customTitleView addSubview:titleLabel];
Run Code Online (Sandbox Code Playgroud)

所以我的tableView:viewForHeaderInSection:方法看起来像......

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

    UIView *customTitleView = [ [UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 44)];
    UILabel *titleLabel = [ [UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 44)];
    titleLabel.text = @"<Title string here>";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    [customTitleView addSubview:titleLabel];
    return customTitleView;
}
Run Code Online (Sandbox Code Playgroud)

我们应该添加tableView:heightForHeaderInSection:为标题提供一些空间的方法.

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{
    return 44; 
}
Run Code Online (Sandbox Code Playgroud)