【问题标题】:Why is NSLayoutAttributeCenterX centering around 0 instead of container view center?为什么 NSLayoutAttributeCenterX 以 0 为中心而不是容器视图中心?
【发布时间】: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


    【解决方案1】:

    有很多代码可以做一些可以在您的 xib 文件中更轻松地完成的事情。我的建议是删除所有代码并使用自动布局在您的 xib 中进行设置。如果您使用自动布局,请不要调用 sizeToFit,只需在包含您的文本的标签上设置前导和尾随约束。您应该不需要实现 layoutSubviews 来实现这一点。

    【讨论】:

      【解决方案2】:

      您不应在-layoutSubviews 中添加或修改约束。来自docs

      仅当子视图的自动调整大小和基于约束的行为不能提供您想要的行为时,您才应覆盖此方法。

      相反,您应该在 -updateConstraints 的覆盖中设置约束。当你覆盖这样的方法时,不要忘记打电话给super。 (这实际上也可能导致您的问题。您对-layoutSubviews 的覆盖不会调用super。)

      【讨论】:

      • 我尝试将约束放在 -updateConstraints 方法中,但结果相同。无论如何,谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多