How do I animate a NSLayoutConstraint in Swift?

天大地大妈咪最大 提交于 2019-11-27 06:40:07

问题


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?


回答1:


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:

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




回答2:


Please set your constraint in viewDidAppear and try below correction

myConstant = 100
myConstraint.constant = myConstant
UIView.animateWithDuration(1, animations: {
self.view.layoutIfNeeded()
}, completion: {finished in })


来源:https://stackoverflow.com/questions/28329042/how-do-i-animate-a-nslayoutconstraint-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!