5

I'm trying to increase my custom keyboard' height in an animation with the following code. But I can't figure out why the change occures instantly, ignoring the animation.

//In viewDidAppear

[self.view needsUpdateConstraints];
[UIView animateWithDuration:2 animations:^{ 
     CGFloat _expandedHeight = 500;
     NSLayoutConstraint *_heightConstraint = [NSLayoutConstraint 
          constraintWithItem: self.view 
          attribute: NSLayoutAttributeHeight 
          relatedBy: NSLayoutRelationEqual
          toItem: nil 
          attribute: NSLayoutAttributeNotAnAttribute
          multiplier: 0.0 
          constant: _expandedHeight];
     [self.view addConstraint: _heightConstraint];
     [self.view layoutIfNeeded];
}];
Drico
  • 1,284
  • 15
  • 33

3 Answers3

0

First add the contraints outside the animation block ,then call for updateConstraints, and inside the animation block , call layoutIfNeeded .Hope this will work

 CGFloat _expandedHeight = 500;
 NSLayoutConstraint *_heightConstraint = [NSLayoutConstraint 
      constraintWithItem: self.view 
      attribute: NSLayoutAttributeHeight 
      relatedBy: NSLayoutRelationEqual
      toItem: nil 
      attribute: NSLayoutAttributeNotAnAttribute
      multiplier: 0.0 
      constant: _expandedHeight];
 [self.view addConstraint: _heightConstraint];
[self.view needsUpdateConstraints];
[UIView animateWithDuration:2 animations:^{ 

 [self.view layoutIfNeeded];
}];
Nassif
  • 1,113
  • 2
  • 14
  • 34
0

The below is a code i use to animate a line's centre X position. I have connected the centre X of this line with some reference view's centre using an IBOutlet NSLayoutConstraint. Inorder for animations to occur with autolayout is need to update the constraint and the call the layoutIfNeeded inside the animation block. This is definitely the idea of animation with autolayout.

    blueScrollerCenterXConstraint.constant = (btn.tag - 4000)*btn.frame.size.width;
   [blueScroller updateConstraints];

   [UIView animateWithDuration:0.3 animations:^{
    [blueScroller layoutIfNeeded];
}];
Nassif
  • 1,113
  • 2
  • 14
  • 34
0
  1. You should not add the constraint there.

  2. Add it and disable it (or set a priority really really low).

  3. After that, change the priority to 999 and call layoutIfNeded in the animation block.

facumenzella
  • 559
  • 3
  • 10