0

Something special has to be done to animate a constraint instantiated programmatically?

I instantiate a constraint programmatically as a lazy variable:

private lazy var topConstraint: NSLayoutConstraint = {
    let constraint = view.topAnchor.constraint(equalTo: otherView.topAnchor, constant: otherView)
    return constraint
}()

Then, I animate a change in the constant of this constraint:

topConstraint.constant = newValue
view.setNeedsLayout()
UIView.animate(withDuration: 1) {
    self.view.layoutIfNeeded()
}

It is not working... I also have tried putting the constant setting into the block:

UIView.animate(withDuration: 1) {
    self.topConstraint.constant = newValue
    self.view.setNeedsLayout()
    self.view.layoutIfNeeded()
}

But I achieved nothing at all, I've tried almost all the combinations. The constraint constant is properly changed, but always without animation.

PD: I also gave a shot to UIViewPropertyAnimator.

Sergio
  • 1,610
  • 14
  • 28
  • 1
    Possible duplicate of [How do I animate constraint changes?](https://stackoverflow.com/questions/12622424/how-do-i-animate-constraint-changes) – Shamas S Sep 10 '19 at 09:48
  • No, this question asks if there is something special to do when the constraint is created by code... No storyboard. – Sergio Sep 10 '19 at 09:51
  • 1
    First, you set `constant: otherView` ... that should be a `CGFloat`, not a reference to a view. Second, are you ever setting `topConstraint.isActive = true`? – DonMag Sep 10 '19 at 12:01

1 Answers1

1

No need for setNeedsLayout().

self.topConstraint.constant = 0.0
UIView.animate(withDuration: 1.0) {[weak self] in
    self?.topConstraint.constant = 10.0 
    self?.view.layoutIfNeeded()
}
PGDev
  • 23,751
  • 6
  • 34
  • 88