Buy*_*ian 5 objective-c ios autolayout
是否可以在运行时更改自动布局约束?
我知道你可以改变常数,但你会如何改变不同的属性.
例如,NSLayoutAttributeTop到NSLayoutAttributeBottom?
这是我希望实现的一个简单示例,它将在左上角设置一个标签,然后当您按下一个按钮时,它会将标签设置在右下方.
初始约束按预期工作,点击按钮不能按预期工作,并抛出臭名昭着的"无法同时满足约束".
这是我正在使用的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setTranslatesAutoresizingMaskIntoConstraints:NO];
self.constraintA = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0];
self.constraintB = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0.0];
[self.view addConstraint:self.constraintA];
[self.view addConstraint:self.constraintB];
}
- (IBAction)tappedChange:(id)sender
{
[self.view removeConstraints:@[ self.constraintA, self.constraintB ]];
self.constraintA = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:0.0];
self.constraintB = [NSLayoutConstraint constraintWithItem:self.topLabel
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0.0];
[self.view addConstraint:self.constraintA];
[self.view addConstraint:self.constraintB];
[self.view setNeedsLayout];
}
Run Code Online (Sandbox Code Playgroud)
感谢您的时间.
您只需要在iOS 7及更低版本上执行删除/重新创建/添加约束舞蹈.如果您正在为现代iOS(8及更高版本)编写,则可以立即创建所有约束,然后在任何给定时间将.active属性设置为NSLayoutConstraint您想要的任何实例.
// Move to right
self.leadingConstraint.active = false;
self.trailingConstraint.active = true;
// Move to bottom
self.topConstraint.active = false;
self.bottomConstraint.active = true;
Run Code Online (Sandbox Code Playgroud)

如果使用Interface Builder,则可以创建所需的所有约束(请注意默认情况下未处于活动状态的灰色约束).
然后,当按下按钮时,您可以停用旧约束并激活新约束.
如果您不确定要显示的视图,可以暂停应用程序执行并在调试器中使用以下私有API来打印出完整的视图和约束列表:
po [[UIWindow keyWindow] _autolayoutTrace]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
526 次 |
| 最近记录: |