65

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

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

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

4

4 回答 4

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

在 iOS 9 中,您还可以NSLayoutConstraint这样创建:

[self.button.topAnchor constraintEqualToAnchor:self.topLayoutGuide.bottomAnchor
                                      constant:20.0];
于 2013-11-04T23:22:49.363 回答
6

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

self.button.topAnchor
    .constraintEqualToAnchor( self.topLayoutGuide.bottomAnchor ).active = true

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

于 2016-03-23T20:40:44.617 回答
3

这是我创建的一个要点,您应该将所有子视图嵌入到添加到 xib 的坦克视图(容器视图)中,它删除了 tank view-superview xib 约束并向 topLayoutGuide 添加了一个上限约束,从而提供 iOS6 外观。你想要实现的目标可能很有趣。

//This should be added before the layout of the view
- (void) adaptToTopLayoutGuide {
    //Check if we can get the top layoutguide
    if (![self respondsToSelector:@selector(topLayoutGuide)]) {
        return;
    }
    //tankView is a contaner view
    NSArray * array = [self.tankView referencingConstraintsInSuperviews]; //<--For this method get the Autolayout Demistified Book Sample made by Erica Sadun
    [self.view removeConstraints:array];
    NSArray * constraintsVertical = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[topLayoutGuide]-0-[tankView]|" options:0 metrics:nil views:@{@"tankView": self.tankView, @"topLayoutGuide":self.topLayoutGuide}];
    [self.view addConstraints:constraintsVertical];
    NSArray * constraintsHorizontal = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tankView]|" options:0 metrics:nil views:@{@"tankView": self.tankView}];
    [self.view addConstraints:constraintsHorizontal];

}
于 2013-10-04T07:40:17.417 回答
3

只是对@Jamie McDaniel 的补充,如果不是很明显,您需要添加他建议创建的约束:

NSLayoutConstraint *buttonTopConstraint = [NSLayoutConstraint constraintWithItem:self.button
                                 attribute:NSLayoutAttributeTop
                                 relatedBy:NSLayoutRelationEqual
                                    toItem:self.topLayoutGuide
                                 attribute:NSLayoutAttributeBottom
                                multiplier:1.0
                                  constant:20.0];
[self.view addConstraint:buttonTopConstraint];
于 2016-04-05T22:46:53.877 回答