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

标签 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];

它在中间垂直对齐并偏向左侧。

我的设置有什么问题吗?

最佳答案

您使用 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 是要使用的正确常量,而不是您最初使用的 ALAxisHorizo​​ntal。要了解原因,请查看 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)
};

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

Illustration of aligning a view to its superview using ALAxisVertical

当您了解 ALAxis 常量的定义方式并从视觉上考虑它时,它是有道理的(您会发现它与这些常量在整个 API 中的使用方式一致)。

关于ios - UIView+Autolayout 没有给我正确的定位——我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816667/

相关文章:

ios - 在 swift 中使用 objective c 协议(protocol)

ios - 类型转换大 NSInteger float 问题

iphone - 如何可靠地找到 UIGestureRecognizer 的正确 View ?

ios - 如何按日期对 nsmutabledictionary 进行排序

ios - 在 ARC 中对局部变量使用 __weak

ios - 是否可以从应用程序本身访问应用程序的推送通知状态?

ios - NSData 长度 - 隐式转换会丢失整数精度

ios - 如何使用为其他UIViewController生成UITableView?

ios - Swift:以动态方式垂直对齐父 View 中心的 subview ?使用人工计算?最好使用 SKSpriteNodes?

ios - 如何将自定义 View 动画化为自定义 View