UIView + Autolayout没有给我正确的定位 - 我做错了什么?

时间:2014-02-16 21:10:05

标签: ios objective-c uiview autolayout nslayoutconstraint

我正在使用UIView+Autolayout库来更轻松地创建基于代码的自动布局约束,但是我在使用此库添加约束时遇到了问题。

我想做的是:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.captionLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.captionLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];

使用普通的NSLayoutConstraint添加方法,它工作得很漂亮。但是当我尝试用UIView + Autolayout做类似的事情时:

[self.captionLabel autoAlignAxisToSuperviewAxis:ALAxisHorizontal];
[self.captionLabel autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:20.0];

它在垂直中间和左侧对齐。

我在设置这个时做错了什么?

1 个答案:

答案 0 :(得分:2)

您使用NSLayoutConstraint API共享的代码:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.captionLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.captionLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]];

将使用UIView+AutoLayout API转换为以下内容:

[self.captionLabel autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0.0];
[self.captionLabel autoAlignAxisToSuperviewAxis:ALAxisVertical];

请注意,ALAxisVertical是正确使用的常量,而不是您最初使用的ALAxisHorizontal。要了解原因,请查看comments where this enum is defined

typedef NS_ENUM(NSInteger, ALAxis) {
    ALAxisVertical = NSLayoutAttributeCenterX,      // a vertical line through the center of the view
    ALAxisHorizontal = NSLayoutAttributeCenterY,    // a horizontal line through the center of the view
    ALAxisBaseline = NSLayoutAttributeBaseline      // a horizontal line at the text baseline (not applicable to all views)
};

如果您对齐两个视图的垂直轴,就像我们在这里做的那样,您最终会调整它们的x位置和/或大小,以便它们最终(您可能描述为)水平居中。这可能是一些混乱所在。一如既往,一张图片胜过千言万语:

Illustration of aligning a view to its superview using ALAxisVertical

当你理解如何定义ALAxis常量并在视觉上思考它时,它是有意义的(你会发现它与这些常量在整个API中的使用方式一致)。