iPhone 6模拟器:
iPhone5硬件:
频道标题:
- (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中的Tableview框架:
<UITableView: 0x7fce2c821a00; frame = (0 0; 414 736)
编辑:
所以我改变了我的模拟笔尖尺寸来自&#34; iPhone 6&#34;到&#34;推断&#34;,并且视图边界增长。我拉伸了我的UITableView以适应边界,现在文本甚至更多偏离中心。所以不知怎的,它的框架得到了错误的值..
答案 0 :(得分:1)
嗯,iPhone 6的框架是错误的。
iPhone 6 屏幕尺寸为 375 x 667 点。
iPhone 6 plus 屏幕尺寸 414 x 736 点。
因此,如果您在iPhone 6模拟器上运行该应用程序并且tableView框架为您提供了iPhone 6 plus边界,那么这就是错误。您的标题和UILabel正在根据给定的帧正确呈现。
因此,如果您在iPhone 6 plus模拟器中运行应用程序,您将获得正确的结果。
<强>解决方案:强>
如果您通过笔尖设置tableView,并且使用AutoLayout,则需要相应地应用约束。
如果您已禁用AutoLayout,则将适当的大小调整掩码应用于tableView,即灵活高度&amp; 灵活宽度
此外,如果您获取委托方法提供的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;
}
注意:这只是一个很好的做法,它不会影响逻辑或答案。
答案 1 :(得分:0)
虽然我等待您对上述评论的回复,但我确定我知道您遇到问题的原因。
如果你想创建具有居中标签的UITableViewCell,那么实际上只有两种正确的方法。
或者:
子类UITableViewCell
并创建一个自定义子类,其中包含一个本地居中的标签。
将常规NSTextAlignment
textLabel控件的UITableViewCell
设置为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;
}