我正在使用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];
它在垂直中间和左侧对齐。
我在设置这个时做错了什么?
答案 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位置和/或大小,以便它们最终(您可能描述为)水平居中。这可能是一些混乱所在。一如既往,一张图片胜过千言万语:
当你理解如何定义ALAxis
常量并在视觉上思考它时,它是有意义的(你会发现它与这些常量在整个API中的使用方式一致)。