在代码中创build自动布局约束到topLayoutGuide和bottomLayoutGuide

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

有没有办法创build这些约束没有 VFL编程(使用NSLayoutConstraint的其他API或类似的)?

(注意:我特别要求在代码中这样做,而不是在Interface Builder中,而且我不希望将指南的计算length作为约束的静态常量,我想要一个约束来更改布局指南长度会自动导致受限视图调整位置。)

对于你想要放置在UIViewController.topLayoutGuide 20个点的UIButton ,你可以这样创buildNSLayoutConstraint

 [NSLayoutConstraint constraintWithItem:self.button attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.topLayoutGuide attribute:NSLayoutAttributeBottom multiplier:1.0 constant:20.0]; 

在iOS 9中,你也可以这样创buildNSLayoutConstraint

 [self.button.topAnchor constraintEqualToAnchor:self.topLayoutGuide.bottomAnchor constant:20.0]; 

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

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

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

这是我创build的一个要点 ,你应该把所有的子视图embedded到一个xib中的坦克视图(容器视图)中,它将删除坦克视图 – 超级视图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]; } 

只是@Jamie McDaniel的一个补充,万一它不是很明显,你需要添加他build议创build的约束:

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