在代码中为topLayoutGuide和bottomLayoutGuide创建自动布局约束

smi*_*org 64 ios autolayout nslayoutconstraint

Apple 关于在视图和其中一个布局指南之间创建自动布局约束的文档仅显示了使用VFL的示例.

有没有办法在没有 VFL(使用NSLayoutConstraint其他API或类似的)的情况下以编程方式创建这些约束?

(注意:我特别要求在代码中执行此操作,而不是在Interface Builder中.我不希望length将指南集的计算设置为约束的静态常量,我想要一个约束,其中布局指南的长度发生变化会自动导致约束视图调整位置.)

Jam*_*iel 93

对于UIButton你想要放置20点以下的那个UIViewController.topLayoutGuide你创建的NSLayoutConstraint像这样:

[NSLayoutConstraint constraintWithItem:self.button
                             attribute:NSLayoutAttributeTop
                             relatedBy:NSLayoutRelationEqual
                                toItem:self.topLayoutGuide
                             attribute:NSLayoutAttributeBottom
                            multiplier:1.0
                              constant:20.0];
Run Code Online (Sandbox Code Playgroud)

使用iOS 9,您也可以这样创建NSLayoutConstraint:

[self.button.topAnchor constraintEqualToAnchor:self.topLayoutGuide.bottomAnchor
                                      constant:20.0];
Run Code Online (Sandbox Code Playgroud)

  • 你(一半?)对.您的代码确实有效,但不需要`NSLayoutAttributeBaseline`来使其工作.如果您固定在`topLayoutGuide`上,那么`NSLayoutAttributeBottom`的工作方式是相同的(当然,当固定到`bottomLayoutGuide`时应该使用`NSLayoutAttributeTop`).无论如何......我以为我之前尝试过这种方法并且它不起作用...猜我搞砸了什么. (9认同)

Sui*_*oth 6

为了补充@ JamieMcDaniel的答案,Swift + iOS9版本将是:

self.button.topAnchor
    .constraintEqualToAnchor( self.topLayoutGuide.bottomAnchor ).active = true
Run Code Online (Sandbox Code Playgroud)

不要忘记该.active = true部分,否则约束不会自动启动.