objective-c - UITableView:viewForHeaderInSection - 标题文本?

标签 objective-c xcode uitableview

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

现在,是时候在这些列上放置标题了。在“viewForHeaderInSection”委托(delegate)中,我想放置一个扩展表格宽度的标签。

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

但是当我去使用时:

label.text = [NSString stringWithFormat:@"  Date      Dist       Litres        Cost($)"];

我没有将文本展开来代表上面的示例。我得到的更像是:

" Date Dist Litres Cost($)"

如何恢复标题文本中所需的空格?

最佳答案

您应该创建一个具有四个 UILabel subview 的标题 View 。

类似这样的事情:

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

根据您的要求调整颜色、字体和框架。

这比依赖空格字符的宽度要干净得多。
如果您使用固定宽度字体,您的方法将会起作用,但我建议不要这样做。

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

关于objective-c - UITableView:viewForHeaderInSection - 标题文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16251103/

相关文章:

objective-c - 如何将UINavigationBar后退按钮的标题更改为 "Back"

ios - 如何测试自定义单元格是否已在 tableView 中注册?

ios - 使用自动布局应用与兄弟 View 相同的垂直位置

ios - block 中的 block 不执行

Objective-C 访问器方法和自动释放的使用

xcode - 在 Swift Cocoa 中,如何请求一次提升的权限而不需要再次请求?

Xcode 助理编辑器已禁用

ios - 可以让 ivar 存储对所有者的引用吗?

ios - tableView.reloadRows(at : [indexPath], with : . none) 会像这样崩溃吗?

iOS - Objective-C 无法使具有标识符的单元格出队