Auto constraint linking with dynamic variable?
Is it possible to have auto layout ( NSLayoutConstraint
) constraint with dynamic constant / multiplier?
For example, this would be the standard god NSLayoutConstraint
:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:obj1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:obj2 attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
Then here would be a change to this constraint, but a dynamic variable in a constant:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:obj1 attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:obj2 attribute:NSLayoutAttributeLeft multiplier:1 constant:scrollView.contentOffset.x];
The second one will accept contentOffset
scrollview
and use it as a constant. However, after trying this, it only uses the offset that exists when the constraint is created.
What I would like it to have a constraint that updates the constant when the scroll is viewed while scrolling. Thus, he will continue to use the most modern contentOffset
.
Is it possible? Thank.
Yes, absolutely.
In fact, that's what they were created for. When you animate views, etc., you should be able to change the constraints.
Counterintuitively, the only property NSLayoutConstraint
that is writable is the property constant
. (Laughs)
However, you are not entirely correct in your code.
Once you create a constraint, you will 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 subview to display ...
[self.view layoutIfNeeded];