为什么tableVieW:viewForHeaderInSection忽略了我的UILabel的frame属性?

16

我想要改变我的区域标题的字体和颜色,所以我实现了 tableView:viewForHeaderInSection。起初我尝试了这段代码:

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel* headerLabel = [[[UILabel alloc] init] autorelease];
    headerLabel.frame = CGRectMake(10, 0, 300, 40);
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.textColor = [UIColor blackColor];
    headerLabel.font = [UIFont boldSystemFontOfSize:18];
    headerLabel.text = @"My section header";

    return headerLabel;
}

但出于某种原因,frame属性被忽略了(我指的是左侧的10像素插入)。现在我使用以下方法:

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView* headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)] autorelease];

    UILabel* headerLabel = [[UILabel alloc] init];
    headerLabel.frame = CGRectMake(10, 0, 300, 40);
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.textColor = [UIColor blackColor];
    headerLabel.font = [UIFont boldSystemFontOfSize:18];
    headerLabel.text = @"My section header";

    [headerView addSubview:headerLabel];
    [headerLabel release];

    return headerView;
}

有了期望的结果。可以有人解释一下为什么第二种方法有效而第一种方法无效吗?

PS. 在两种情况下,我都实现了tableView:heightForHeaderInSection,并返回40.0。

2个回答

26

这是由于UITableView会自动设置您提供的表头视图的框架为

(0,y,table view宽度,header view高度)

y是视图的计算位置, header view高度tableView:heightForHeaderInSection:返回的值。


那么我在代码中真的需要“headerView”才能获得这个插入,对吗? - phi
5
在标签文本前面添加一些空格也可以起到快速调整UILabel的好效果。 - Bogatyr
这在我的情况下在iOS 7中表现不同。它会在iOS 7中的headerView两侧添加1个pt的填充。你们有看到相同的情况吗? - Koolala

2
也许更好的做法是添加一个子视图:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
    let label = UILabel(frame: CGRect(x: 15, y: 5, width: tableView.frame.width, height: 20))
    label.text = "\(sections[section].year)"
    view.addSubview(label)
    return view
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接