Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to update auto layout constant?

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

like image 794
NOrder Avatar asked Dec 20 '22 23:12

NOrder


2 Answers

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];
}];
like image 56
Mike Pollard Avatar answered Dec 28 '22 08:12

Mike Pollard


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.

like image 21
uchuugaka Avatar answered Dec 28 '22 06:12

uchuugaka