AnimateWithDuration doesn't work as expected

I'm trying to run an example to test this function. I have a label an a button in the storyBoard and I have referenced the bottom constraint of the label in the view controller. When I use the button I want the label to move with an animation but it moves without it. Here's the code of the button:

- (IBAction)sd:(id)sender {
[UIView animateWithDuration:0.5f animations:^{
    self.constraint.constant += 50;
}];
}

I know how to use it in swift but I'm having problems in objective c and I know it will be just for a little mistake... Any help?

Upvotes: 2

Views: 505

Answers (3)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52213

This is not the right way of animating a UI component constrained with Autolayout. You should first update the constraint, then call layoutIfNeeded within the animation block:

self.constraint.constant += 50;
[UIView animateWithDuration:0.5f animations:^{
  [self.view layoutIfNeeded];
}];

Upvotes: 2

Clown
Clown

Reputation: 183

Try this setNeedsLayout helps in some cases.

self.constraint.constant += 50;
[UIView animateWithDuration:0.5f
                 animations:^{
                      [self.view setNeedsLayout];
                  }
                  completion:^(BOOL finished) {

                  }];

Upvotes: 0

Sunny Shah
Sunny Shah

Reputation: 13020

Use this

 self.constraint.constant += 50;
    [UIView animateWithDuration:0.5f
        animations:^{
            [self.view layoutIfNeeded]; 
        }];

Upvotes: 1

Related Questions