1

I'm trying to animate constraints in my ViewController. In order to do that, I added this line to my code: I'm just trying to change the height of a UIView() (from 0 to 100)

barHeight.constant = CGFloat(100)
UIView.animate(withDuration: 2) {self.view.layoutIfNeeded()}

The problem is that, with that line, all of the constraints are animated, and it's not what I would like.

Do you know how I could animate only specific constraints and not others?

KevinB
  • 2,454
  • 3
  • 25
  • 49
  • 3
    Show. Your. Code! – matt Apr 09 '19 at 17:26
  • 1
    You need to show what you're doing. Is it simply that you have constraints to the view you are changing? As in, you animate the `topAnchor` constraint of a view, and that view has a `bottomAnchor` constrain to another view? – DonMag Apr 09 '19 at 17:28

1 Answers1

4

Call layoutSubviews before you edit the constraint you want to animate. This will cause any pending layout updates to be applied without any animation and then you can change the next constraint with animation.

Like so:

 self.view.layoutSubviews()
 barHeight.constant = CGFloat(100)
 UIView.animate(withDuration: 2) {self.view.layoutIfNeeded()}
Isaiah Turner
  • 2,574
  • 1
  • 22
  • 35
  • 1
    I still have everything animating –  Jun 25 '20 at 03:44
  • 1
    according to the following [answer](https://stackoverflow.com/a/12664093/10022404) you need to call `layoutIfNeeded()` instead of `layoutSubviews()`. at least it helped me – dywp Mar 04 '21 at 13:16