如何将其他视图与 UITableViewCell 的 textLabel 对齐?

How do you align other views with a UITableViewCell's textLabel?

我为我的 table.tableHeaderView 创建了一个文本标签,我希望它与我的标准 UITableViewCell.textLabel 中的文本一样左对齐。如何获得正确的 X 偏移量?

cell.indentationWidth 是 10 而 cell.indentationLevel = 0 但这显然不是全部。在 cellForRowAtIndexPath:willDisplayCell: tableView 方法中,UITableViewCell.textLabel 的 X 原点是 0.

我可以提前确定 cell.textLabel 的 X 原点吗?或者我是否必须获取它然后找到相对于 tableView 的原点然后更新我的 headerLabel 的 X 原点?

在此处下载 sample project

@implementation ViewController {
    UILabel *headerTextLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"myId"];

    CGRect headerFrame = CGRectMake(0, 0, self.tableView.bounds.size.width, 100); // arbitrary height
    UIView *header = [[UIView alloc] initWithFrame:headerFrame];
    header.backgroundColor = [UIColor lightGrayColor];
    self.tableView.tableHeaderView = header;

    CGFloat xHeaderLabel = 0; // What do I set this to?

    // header text label should be left-aligned and match the cell text
    headerTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(xHeaderLabel, 0, 300, 40)]; // arbitrary header size
    headerTextLabel.text = @"Header text -- align with cells";
    headerTextLabel.backgroundColor = [UIColor orangeColor];
    [header addSubview:headerTextLabel];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myId"];
    cell.textLabel.text = [NSString stringWithFormat:@"Cell %ld", (long)indexPath.row];
    cell.textLabel.backgroundColor = [UIColor redColor];
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.backgroundColor = [UIColor redColor];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

查看 UITableView 上的分隔符插图:

 NSLog(self.tableView.separatorInset.left);  // -> 15.0