在我的应用程序(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/