【发布时间】:2015-02-23 10:04:24
【问题描述】:
我对 NSLayoutAttributeCenterX 有一个我无法弄清楚的问题。 我为自定义视图创建了一个 NIB,并在此自定义视图中插入了一个 UILabel,我想在 x 轴上居中。然后我将这个自定义视图插入到我的根 ViewController 的视图中。 现在,我重写了自定义视图的“layoutSubviews”方法,将我的约束放在那里,使标签在自定义视图中居中。 我将此视图中的 UILable 称为“appTitle”。 下面是我自定义视图的“layoutSubviews”方法的内容。如您所见,我使用以下约束方法将 UILabel 置于自定义视图的中心,在 x 轴上。
NSLayoutConstraint *titleConstraint_H = [NSLayoutConstraint constraintWithItem:self.appTitle attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
但是,最终结果是 UILabel 以 x= 0 为中心,而不是 x = 160,后者是包含它的自定义视图的中心。我不明白为什么会这样。 在我的模拟中,我在 PORTRAIT MODE 中使用 ipHone 5s,并且我将自定义视图的宽度设置为等于手机框架的宽度,即 320。因此 x = 160 是中心的 x 坐标点。
- 下面是“layoutSubviews”中的代码
- LLDB 输出显示约束生效后 appTitle 标签的中心 (po (CGPoint) [self.appTitle center])
- LLDB 输出显示包含标签“appTitle”的自定义视图的中心 (po (CGPoint)[self center])
- 和最终输出
我想知道是否有人也遇到过这个问题并且已经解决了
- (void)layoutSubviews {
//######### TITLE ####################################
UIFont *font = [UIFont fontWithName:@"Avenir-Black" size:20.0];
UIColor *color = [UIColor blackColor];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjects:@[font,color] forKeys:@[NSFontAttributeName,NSForegroundColorAttributeName]];
NSAttributedString *titleString = [[NSAttributedString alloc] initWithString:@"WHINE-O-METER" attributes: attrsDictionary];
self.appTitle.attributedText = titleString;
// Adjust UILabel frame to size of text
[self.appTitle sizeToFit];
// Center title on horizontal length
NSLayoutConstraint *titleConstraint_H = [NSLayoutConstraint constraintWithItem:self.appTitle attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
NSDictionary *viewsDictionary = @{ @"title":self.appTitle};
NSArray *titleConstraint_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[title]-20-|" options:0 metrics:nil views:viewsDictionary];
[self addConstraints:titleConstraint_V];
[self addConstraint:titleConstraint_H];
}
谢谢!
【问题讨论】:
标签: ios centering nslayoutconstraint