如何在Swift中为NSLayoutConstraint设置animation?

我的目标是animation一个UIImageView 。 我在viewDidLoad声明了一个NSLayoutConstraint 。 在viewDidLoad ,我使用了这个代码:

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

为什么我的形象不移动?

当你点击viewDidLoad ,约束引擎还没有被应用,视图的起始位置还没有build立。 所以,可以在viewDidLoad添加原始的约束条件,但是你需要延迟animateWithDuration直到后面的过程(比如viewDidAppear )。


例如,假设您在Interface Builder(IB)中添加了一些约束条件。 您可以通过从Interface Builder左侧面板中文档大纲中的约束控制向下拖动到助理编辑器来添加@IBOutlet引用:

在这里输入图像说明

现在你有了对这个约束的引用,现在你可以通过编程来改变这个约束的constant量值了(但是,如果你想在视图被呈现的时候看到这个animation,那么在viewDidAppear而不是viewDidLoad做这个):

 @IBOutlet weak var topConstraint: NSLayoutConstraint! override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) topConstraint.constant = 100 UIView.animateWithDuration(2.0) { self.view.layoutIfNeeded() } } 

该过程对于以编程方式创build的约束是相同的。 只需保存对约束的引用,然后在viewDidAppear更新constant ,然后将调用animationlayoutIfNeeded()

请在viewDidAppear中设置你的约束,并尝试下面的更正

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