如何在Swift中为NSLayoutConstraint设置动画? [英] How do I animate a NSLayoutConstraint in Swift?
问题描述
我的目标是为 UIImageView
设置动画。我在 viewDidLoad
中声明了 NSLayoutConstraint
。在 viewDidLoad中
中,我使用这个代码:
My goal is to animate a UIImageView
. I declared a NSLayoutConstraint
in viewDidLoad
. In viewDidLoad
, I used this code:
UIView.animateWithDuration(1, animations: {
myConstraint.constant = 100
self.view.layoutIfNeeded()
}, completion: {finished in })
为什么我的图像不移动?
Why doesn't my image move?
推荐答案
按点击 viewDidLoad
的时间,尚未应用约束引擎,并且尚未建立视图的起始位置。因此,随意添加在 viewDidLoad中
原来的限制,但你会希望稍后推迟 animateWithDuration
直到过程(例如 viewDidAppear
)。
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
).
例如,让我们假设您在Interface Builder(IB)中添加了一些约束。您可以通过 control 添加 @IBOutlet
引用 - 从Interface Builder左侧面板中的文档大纲中的约束拖拽到助理编辑:
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:
现在您有参考对于该约束,您现在可以以编程方式更改该约束的常量
值(但是,再次在 viewDidAppear
中执行此操作,而不是 viewDidLoad
,如果你想在视图出现时看到这个动画):
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.animateWithDuration(2.0) {
self.view.layoutIfNeeded()
}
}
对于以编程方式创建的约束,该过程是相同的。只需保存对约束的引用,然后在 viewDidAppear
中更新常量
,然后将调用设置为<$ c $。 c> 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()
.
这篇关于如何在Swift中为NSLayoutConstraint设置动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!