如何在Swift中为NSLayoutConstraint设置动画?

时间:2015-02-04 18:46:46

标签: ios swift nslayoutconstraint

我的目标是为UIImageView制作动画。我在NSLayoutConstraint中声明了viewDidLoad。在viewDidLoad中,我使用了以下代码:

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

为什么我的图片没有移动?

2 个答案:

答案 0 :(得分:35)

当您点击viewDidLoad时,尚未应用约束引擎,并且尚未建立视图的起始位置。因此,您可以随意在viewDidLoad中添加原始约束,但是您需要将animateWithDuration推迟到此过程的后期(例如viewDidAppear)。


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

enter image description here

现在您已经引用了该约束,现在可以通过编程方式更改该约束的constant值(但是,请再次在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()
    }
}

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

答案 1 :(得分:8)

请在viewDidAppear中设置约束并尝试以下修正

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