简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM