Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate anchor style constraints in iOS9.0

Using the anchor style NSLayoutConstraints (as in this answer: Swift | Adding constraints programmatically) how can I animate the subviews?

For those who are lazy here is the code:

override func viewDidLoad() {
    super.viewDidLoad()

    let newView = UIView()
    newView.backgroundColor = UIColor.redColor()
    newView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(newView)

    let horizontalConstraint = newView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor)
    let vertivalConstraint = newView.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor)
    let widthConstraint = newView.widthAnchor.constraintEqualToAnchor(nil, constant: 100)
    let heightConstraint = newView.heightAnchor.constraintEqualToAnchor(nil, constant: 100)
    NSLayoutConstraint.activateConstraints([horizontalConstraint, vertivalConstraint, widthConstraint, heightConstraint])
}

Specifically, if I want to slide newView right how would I do it? Thanks.

like image 310
Liumx31 Avatar asked Sep 26 '15 21:09

Liumx31


1 Answers

You'd set your constraint, and then within an animation block, update with layoutIfNeeded:

self.horizontalConstraint.constant += 10 // move right 10 px.
UIView.animateWithDuration(0.5) {
    self.view.layoutIfNeeded()
}
like image 113
Chris Slowik Avatar answered Sep 22 '22 14:09

Chris Slowik