问题
Is it possible to have an Auto Layout constraint (NSLayoutConstraint
) with a dynamic constant/multiplier?
For example, this would be a bog standard NSLayoutConstraint
:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:obj1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:obj2 attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
Then here would be an alteration of that constraint but a dynamic variable in the constant:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:obj1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:obj2 attribute:NSLayoutAttributeLeft multiplier:1 constant:scrollView.contentOffset.x];
The second one would take the contentOffset
of the scrollview
and use it as the constant. However, having tried this, it only uses the offset which exists when the constraint is made.
What I would want it to have the constraint update the constant, when the scrollview if scrolling. This way it would keep using the most up to date contentOffset
.
Is this possible? Thanks.
回答1:
Yes definitely.
In fact, that is what they are built for. When you are animating views etc... you need to be able to change the constraints.
Counter-intuitively the only property of NSLayoutConstraint
that is writable is the constant
property. (lol)
You are not quite right in your code though.
Creating the constraint you would first create a property for it...
@property (nonatomic, strong) NSLayoutConstraint *leftConstraint;
Then create it...
self.leftConstraint = [NSLayoutConstraint constraintWithItem:obj1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:obj2 attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
Then edit the already existing constraint...
self.leftConstraint.constant = scrollView.contentOffset.x;
Then you need to force the view to relayout the subviews...
[self.view layoutIfNeeded];
来源:https://stackoverflow.com/questions/27228279/auto-layout-constraint-with-dynamic-variable