ios - 为什么我的 tableview 标题显示偏离中心?

标签 ios objective-c uitableview uitextfield

iPhone 6 模拟器:image 1

iPhone5 硬件:image2

channel 标题:

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

为什么我的 tableview 标题的文本字段显示偏离中心?

iPhone6 sim 中的表格 View 框架:

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

编辑:

所以我将我的模拟 Nib 大小从“iPhone 6”更改为“推断”,并且 View 边界变大了。我拉伸(stretch)了我的 UITableView 以适应边界,现在文本甚至更多偏离了中心。所以不知何故,它的框架得到了错误的值..

最佳答案

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

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

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

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

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

More info on frames.

解决方案:

如果您通过 nib 设置您的 tableView,并且您正在使用 AutoLayout,那么您需要相应地应用约束

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


此外,如果您采用委托(delegate)方法提供的 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;
}

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

关于ios - 为什么我的 tableview 标题显示偏离中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734154/

相关文章:

ios - Swift - AVFoundation 捕获图像方向

ios - 从 UIScrollView 后面的取消按钮获取操作

ios - Swift Tableview 从 Firebase 数据库加载数据

ios - 自动布局 : UITextFields with equal width in different UITableViewCells

ios - SpriteKit 物理不工作

ios - 在 UITableView 上插入新节或删除节时如何更新 UITableViewDataSource?

ios - 如何从用户函数中获取对单元格的引用

ios - Swift:从 url 下载数据导致 semaphore_wait_trap 卡住

ios - WatchKit WKInterfaceGroup 可以是一个按钮吗?

ios - 如何在不阻塞 UI 的情况下重复调用方法?