AutoLayout 的第一条规则是您不能直接更新视图的frame
,bounds
或center
。
您必须更新与视图相关的约束,以便约束更新视图。
例如,您的第一条垂直线将具有水平约束,例如...
1. Leading edge to superview = some value.
2. Width = some value.
这足以(水平地)将此线放置在屏幕上。
现在,如果你想把这条线移到右边,你不能只改变center
你必须这样做......
1. Create a property in you view controller like this...
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *verticalLine1LeadingConstraint;
// or if you're coding the constraint...
@property (nonatomic, strong) NSLayoutConstraint *verticalLine1LeadingConstraint;
2. Save the constraint in to that property...
// either use IB to CTRL drag the constraint to the property like any other outlet.
// or something like...
self.verticalLine1LeadingConstraint = [NSLayotuConstraint ... // this is the code adding the constraint...
[self.view addConstraint:self.verticalLine1LeadingConstraint];
现在你有一个指向这个约束的属性。
现在,当您需要“更新垂直线 1 的中心”时...
// Calculate the distance you want the line to be from the edge of the superview and set it on to the constraint...
float distanceFromEdgeOfSuperview = // some calculated value...
self.verticalLine1LeadingConstraint.constant = distanceFromEdgeOfSuperview;
[self.view layoutIfNeeded];
这将更新视图的位置,您不会收到任何错误。