1

The below function is just moving the view to a new place. It isn't showing the animation:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    UIView.animate(withDuration: 0.9, animations: {
        //self.leadingConst.constant -= 200

        self.view.setNeedsLayout()
    })
}
Rashwan L
  • 37,198
  • 7
  • 99
  • 103
BostonMacOSX
  • 1,157
  • 2
  • 14
  • 33
  • `self.view.layoutIfNeeded()` is when the actual animation takes place. `setNeedsLayout()` just tells the view i needs to layout in the next pass, but doesn't actually do it. – GetSwifty Sep 01 '17 at 16:45

2 Answers2

1

self.leadingConst.constant -= 200 should be outside UIView.animate, like this:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.leadingConst.constant -= 200
    UIView.animate(withDuration: 0.9, animations: {
        self.view.setNeedsLayout()
    })
}

reference: trying to animate a constraint in swift

Luigi Taira
  • 315
  • 6
  • 8
0

A few weeks ago I ran into the same problem. The problems came down to a few things. I was mixing adding views programmatically and adding them to the storyboard, I wasn't calling layoutSubviews(), and I was adding my constraints as IBOutlets as weak vars. So I would suggest to only use storyboard (otherwise animations start to get complicated quickly) and make your leadingConst constraint a var. You should also move the object that you want to animate in the animation block and then use a completion block to reset the constraint.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    view.layoutSubviews()
    UIView.animate(withDuration: 0.9, animations: {

        //something like this
        self.animatableObject.origin.x -= 200

    }, completion: {(finished: Bool) in

        self.leadingConst.constant -= 200

    })
}

I'm not sure what your trying to animate so the origin.x line is just an example.