未显示 iOS 表视图标题子视图



我使用UITableView,我想在开头设置文本。我的代码是:

UIView *tableHeaderView = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, self.tableView.frame.size.width, 20.0)];
tableHeaderView.backgroundColor = [UIColor groupTableViewBackgroundColor];
UILabel *tableHeaderLabel = [[UILabel alloc]initWithFrame:CGRectMake(15.0,0,tableHeaderView.frame.size.width-15.0,tableHeaderView.frame.size.height)];
tableHeaderLabel.text = @"Countries";
if([UIFont respondsToSelector:@selector(preferredFontForTextStyle:)])
    tableHeaderLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
else
    tableHeaderLabel.font = [UIFont boldSystemFontOfSize:14.0];
[tableHeaderView addSubview:tableHeaderLabel];
self.tableView.tableHeaderView = tableHeaderView;
[tableHeaderView bringSubviewToFront:tableHeaderLabel];
[tableHeaderLabel release];
[tableHeaderView release];

问题是没有显示文本。如果我抑制主标题视图的背景颜色,或者如果我用透明的它替换它,就好像标签在主标题视图下一样。所以我添加了这一行:

[tableHeaderView bringSubviewToFront:tableHeaderLabel];

但这并不能解决问题。我不能直接将标签用作表视图标题视图,因为我想在文本左侧留出空间。

有人有想法可以帮助我吗?

谢谢。

您在这里遇到的唯一问题是第一行的拼写错误,将UIView错误地初始化为UILabel。编译器将不符合UILabel因为 UIView 的子类。

我运行了以下代码,它按预期工作:(该代码适用于 ARC,如果您不使用它,请不要忘记执行release

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0,
                                                                        self.tableView.frame.size.width,
                                                                        20.0)];
    tableHeaderView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UILabel *tableHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.0, 0,
                                                                          tableHeaderView.frame.size.width - 15.0,
                                                                          tableHeaderView.frame.size.height)];
    tableHeaderLabel.text = @"Countries";
    tableHeaderView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    if([UIFont respondsToSelector:@selector(preferredFontForTextStyle:)]) {
        tableHeaderLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
    } else {
        tableHeaderLabel.font = [UIFont boldSystemFontOfSize:14.0];
    }
    [tableHeaderView addSubview:tableHeaderLabel];
    self.tableView.tableHeaderView = tableHeaderView;
}

最新更新