If I need to update a view's frame, I can put that code in -(void)viewWillLayoutSubviews
as following:
- (void)viewWillLayoutSubviews {
self.demoView.frame = CGRectMake(0, 0, 10, 10);
}
or in view's method - (void)layoutSubviews
.
However, if I use autolayout now, and I need to update NSLayoutConstraint
object dynamic in code, I don't know where to put the code like self.demoWidthConstraint = 10
You can adjust existing constraints anywhere, just call layoutIfNeeded
afterwards.
To animate the change do for example:
self.demoConstraint.constant = 10;
[UIView animateWithDuration:duration animations:^(void) {
[self.view layoutIfNeeded];
}];
You need to keep a reference to the constraint. The easiest way to do this is to create an IBOutlet property in Xcode and link it to the constraint in interface builder.
If you create and apply constraints in code you'll write more code but have more flexibility. Particularly with views that are added and removed.
In that case a simple property will work. You'll benefit from some boilerplate code in the viewDidMoveToSuperview method of the view. Check there if superview is nil. If not nil then check if the constraint property is nil. If nil, create it. Then add it to the superview.
Adjust the constraint by the property's constraint property whenever you need to.
One more bit if boilerplate code for when the view is removed from the superview. First remove the constraint then set it to nil.
Now your constraint will always be there when your view is in use and you can adjust the constant or multiplier as appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With