为什么我的表格视图 header 显示 off-center?

Why is my tableview header showing up off-center?

iPhone 6个模拟器:

iPhone5 硬件:

频道Header:

- (id)initWithFrame:(CGRect)frame title:(NSString *)title {
    self = [super initWithFrame:frame];
    UILabel *l = [[UILabel alloc] initWithFrame:frame];
    l.textAlignment = NSTextAlignmentCenter;
    l.backgroundColor = BGC;
    l.text = title;
    [self addSubview:l];
    return self;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ChannelHeader *h = [[ChannelHeader alloc] initWithFrame:CGRectMake(0, 0, self.tv.frame.size.width, 44) title:[self titles][section]];
    return h;
}

为什么我的表格视图 header 的文本字段显示偏离中心?

iPhone6 sim 中的表格视图框架:

<UITableView: 0x7fce2c821a00; frame = (0 0; 414 736)

编辑:

所以我将我的模拟笔尖大小从 "iPhone 6" 更改为 "inferred",并且视图边界变大了。我拉伸了我的 UITableView 以适应边界,现在文本甚至 more off-centered。所以不知何故,它的框架得到了错误的值..

虽然我在等待您对上述评论的回复,但我很确定我知道您遇到问题的原因。

如果你想创建具有居中标签的 UITableViewCell(s),实际上只有两种正确的方法。

或者:

  • 子类 UITableViewCell 并创建一个自定义子类,该子类具有以本地为中心的标签。

  • 将常规 UITableViewCell textLabel 控件的 NSTextAlignment 设置为在 cellForRowAtIndexPath 中居中,如下所示:cell.textLabel!.textAlignment = .Center.

要更改页眉文本对齐方式,您应该这样做:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     UILabel * sectionHeader = [[UILabel alloc] initWithFrame:CGRectZero];
     sectionHeader.backgroundColor = [UIColor clearColor];
     sectionHeader.textAlignment = NSTextAlignmentCenter;
     sectionHeader.font = [UIFont boldSystemFontOfSize:10];
     sectionHeader.textColor = [UIColor whiteColor];
   return sectionHeader;
}

嗯,你的 iPhone 6 框架是错误的。

iPhone 6 屏幕尺寸为 375 x 667 点。

iPhone 6 plus 屏幕尺寸为 414 x 736 点。

因此,如果您 运行 在 iPhone 6 模拟器上运行应用程序并且 tableView 框架为您提供 iPhone 6 加边界,那么这就是错误。您的 header 和 UILabel 正在根据给定的帧正确呈现。

因此,如果您 运行 在 iPhone 6 plus 模拟器中使用您的应用程序,您将获得正确的结果。

More info on frames.

解法:

如果您通过 nib 设置 tableView,并且您使用的是 AutoLayout,那么您需要相应地应用 constraints

如果您禁用了 AutoLayout,则对您的 tableView 应用适当的调整大小蒙版,即 Flexible Height & Flexible Width


此外,如果您采用委托方法提供的 tableView 框架的值而不是引用 tableView,这将是一个很好的做法 属性。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ChannelHeader *h = [[ChannelHeader alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), 44) title:[self titles][section]];
    return h;
}

注意:这只是一个很好的练习,不会影响逻辑或答案。