Liumx31
Liumx31

Reputation: 1210

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.

Upvotes: 5

Views: 5341

Answers (1)

Chris Slowik
Chris Slowik

Reputation: 2879

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()
}

Upvotes: 7

Related Questions