UITableView:viewForHeaderInSection - 标题文本?

Fri*_*les 2 xcode objective-c uitableview

在我的应用程序(iPad)中,需要创建一个包含许多列的UITableView.为此,我必须创建一个自定义UITableViewCell来提供所需的列.

现在,是时候在这些列上放置标题了.在'viewForHeaderInSection'委托中,我想放置一个扩展表宽度的标签.

一切都很顺利,背景颜色已经设置,并且很好地延伸到视图的宽度.

但是当我去使用时:

label.text = [NSString stringWithFormat:@"  Date      Dist       Litres        Cost($)"];
Run Code Online (Sandbox Code Playgroud)

我没有将文本展开以代表上面的例子.我得到的更像是:

" Date Dist Litres Cost($)"
Run Code Online (Sandbox Code Playgroud)

如何在标题文本中恢复我需要的空格?

Mat*_*uch 5

您应该创建一个包含四个UILabel子视图的标题视图.

像这样的东西:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    // 4 * 69 (width of label) + 3 * 8 (distance between labels) = 300
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 69, 22)];
    label1.text = @"Date";
    [headerView addSubview:label1];
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(87, 4, 69, 22)];
    label2.text = @"Dist";
    [headerView addSubview:label2];
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(164, 4, 69, 22)];
    label3.text = @"Litres";
    [headerView addSubview:label3];
    UILabel *label4 = [[UILabel alloc] initWithFrame:CGRectMake(241, 4, 69, 22)];
    label4.text = @"Cost($)";
    [headerView addSubview:label4];
    return headerView;
}
Run Code Online (Sandbox Code Playgroud)

根据您的要求调整颜色,字体和框架.

这将比依赖空格字符的宽度更清晰.
如果你使用固定宽度的字体,你的方式将工作,但我建议反对它.

当您想要将应用程序本地化为不同的语言时,计算空间的任务将成为一场噩梦.