Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLayoutConstraint constant not updating after setting

Tags:

I have a UIView subclass with a corresponding xib file. In my xib I have a NSLayoutConstraint property which I'm trying to animate. I have an animateIn method. The problem is that only the animateIn method works. When I try to update the constant again it simply stays at the previous value.

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *horizontalConstraint; 

I'm trying to update the constant after a button press. But the constant doesn't seem to update after setting. It still logs 0 even after setting it to -500. I'm calling layoutIfNeeded but nothing happens.

// this works - (void) animateIn {      [UIView animateWithDuration:1.0 delay:2.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{         self.alpha = 1.0;     } completion:^(BOOL finished) {          [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{             self.horizontalConstraint.constant = 0;             [self layoutIfNeeded];         } completion:^(BOOL finished) {         }];     }]; }  // this does not work - (IBAction)resume:(id)sender {         self.horizontalConstraint.constant = -500;         [self layoutIfNeeded];          NSLog(@"%f",self.horizontalConstraint.constant); // this always stays 0     } 

UPDATE

It seems that my NSLayoutConstraint is (null) when I want to use it a second time. That would explain why it is not updating. How should I keep a reference to it?

like image 685
Ramin Afshar Avatar asked Aug 11 '14 10:08

Ramin Afshar


2 Answers

You will need to call setNeedsUpdateConstraints method of corresponding UIView(control) of which your NSLayoutConstraint is present to update constraint.

For example of UIButton

self.buttonConstraint.constant = 55; [self.btnTest setNeedsUpdateConstraints]; 

In your case

[self setNeedsUpdateConstraints]; 
like image 136
Yogesh Suthar Avatar answered Sep 22 '22 15:09

Yogesh Suthar


I ran into a problem where the first time I set the constraint constant in code the constant would be set but then after calling layoutIfNeeded(), such as this:

myConstraint.constant = newValue; [view layoutIfNeeded] 

the constant would go back to the original value! I could watch the value change back in the debugger.

I finally figured out that it was because, in the storyboard, I had set a variation on the constant. For example:

enter image description here

As soon as I removed the variation, the constraint constant value did not change back to the original value with layoutIfNeeded call.

like image 24
CLK Avatar answered Sep 19 '22 15:09

CLK