苹果公司有关创建视图和布局指南之间的自动布局约束的文档只展示了一个使用VFL的例子。
是否有一种在编程中不使用VFL(例如使用NSLayoutConstraint
的其他API或类似方法)来创建这些约束的方式?
(注:我特别想要在代码中完成这个问题,不是在Interface Builder中完成。我也不想将计算出的length
设置为约束的静态常量,而是想要一种可以自动调整位置的约束,以响应布局指南长度的变化。)
苹果公司有关创建视图和布局指南之间的自动布局约束的文档只展示了一个使用VFL的例子。
是否有一种在编程中不使用VFL(例如使用NSLayoutConstraint
的其他API或类似方法)来创建这些约束的方式?
(注:我特别想要在代码中完成这个问题,不是在Interface Builder中完成。我也不想将计算出的length
设置为约束的静态常量,而是想要一种可以自动调整位置的约束,以响应布局指南长度的变化。)
如果您想要将UIButton
放置在UIViewController.topLayoutGuide
下方20个点,则可以按以下方式创建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];
NSLayoutAttributeBaseline
。如果你要将其固定到 topLayoutGuide
,则 NSLayoutAttributeBottom
同样适用(当然,当固定到 bottomLayoutGuide
时应该使用 NSLayoutAttributeTop
)。不管怎样...我之前认为尝试过这种方法,但没有成功...可能是我搞错了什么。 - smileyborgself.button.topAnchor
.constraintEqualToAnchor( self.topLayoutGuide.bottomAnchor ).active = true
不要忘记.active = true
这一部分,否则约束条件将无法自动触发。
补充一下@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];
//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];
}