【问题标题】:Why does tableVieW:viewForHeaderInSection ignore the frame property of my UILabel?为什么 tableVieW:viewForHeaderInSection 会忽略我的 UILabel 的 frame 属性?
【发布时间】:2023-04-08 15:38:01
【问题描述】:

基本上我想更改节标题的字体和颜色,所以我实现了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 属性被忽略(我说的是左侧的 10px 插图)。现在我使用以下内容:

-(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

【问题讨论】:

    标签: iphone uitableview frame


    【解决方案1】:

    也许最好添加一个子视图:

    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
    }
    

    【讨论】:

      【解决方案2】:

      那是因为 UITableView 会自动设置你提供的标题视图的框架

      (0, y, table view width, header view height)

      y 是视图的计算位置,并且 header view height是tableView:heightForHeaderInSection:返回的值

      【讨论】:

      • 那我真的需要代码中的“headerView”来获得这个插图,对吧?
      • 在标签中的文本前面添加一些空格也可以,这是快速调整 UILabel 的好方法。
      • 对于我的情况,这在 iOS 7 中的行为有所不同。它在 iOS 7 中为 headerView 的两侧添加了 1 pt 填充。你们看到的一样吗?
      猜你喜欢
      • 1970-01-01
      • 2014-07-10
      • 2012-05-13
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2011-02-09
      • 2010-12-11
      • 2021-12-03
      相关资源
      最近更新 更多