Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

ios - How do I animate a NSLayoutConstraint in Swift?

I would like to animate an UIImageView. I declared a NSLayoutConstraint in viewDidLoad and used this code:

UIView.animate(withDuration: 1) {
    myConstraint.constant = 100
    self.view.layoutIfNeeded()
}

Why doesn't my image move?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By the time you hit viewDidLoad, the constraints engine has not yet been applied and the starting location of the views has not yet been established. So, feel free to add the original constraints in viewDidLoad, but you will want to defer the animateWithDuration until later in the process (e.g. viewDidAppear).


For example, let's assume you have some constraint that you added in Interface Builder (IB). You can add an@IBOutlet reference to it by control-dragging from the constraint in the document outline in the left panel in Interface Builder down to the assistant editor:

enter image description here

Now that you have a reference to that constraint, you can now programmatically alter the constant value for that constraint (but, again, do this in viewDidAppear, not viewDidLoad, if you want to see this animated when the view is presented):

@IBOutlet weak var topConstraint: NSLayoutConstraint!

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

    topConstraint.constant = 100
    UIView.animate(withDuration: 2) {
        self.view.layoutIfNeeded()
    }
}

The process is the same for programmatically created constraints. Just save a reference to the constraint and then in viewDidAppear update the constant and then animate the call to layoutIfNeeded().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...