2017-09-01 46 views
0

下面的函数只是将视图移动到新的位置。它没有显示动画:约束的快速动画不起作用

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    UIView.animate(withDuration: 0.9, animations: { 
     //self.leadingConst.constant -= 200 

     self.view.setNeedsLayout() 
    }) 
} 
+0

'self.view.layoutIfNeeded()'是实际动画发生的时间。 'setNeedsLayout()'只是告诉我需要在下一遍中布局的视图,但实际上并没有这样做。 – PeejWeej

回答

0

self.leadingConst.constant -= 200外应UIView.animate,像这样:

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    self.leadingConst.constant -= 200 
    UIView.animate(withDuration: 0.9, animations: { 
     self.view.setNeedsLayout() 
    }) 
} 

参考:trying to animate a constraint in swift

+0

立即显示到-200位置..没有动画 – BostonMacOSX

0

您需要首先设置约束,然后调用layoutIfNeeded在你的动画。像这样:

self.leadingConst.constant -= 200 
UIView.animate(withDuration: 0.9, animations: { 
    self.view.layoutIfNeeded() 
}) 
0

几周前我遇到了同样的问题。问题归结为几件事情。我以编程方式混合添加视图并将它们添加到故事板,我没有调用layoutSubviews(),并且我将IBOutlets的约束条件添加为弱变量。所以我建议只使用storyboard(否则动画开始变得很快变得复杂),并使你的leadingConst约束变成一个变种。您还应该在动画块中移动想要制作动画的对象,然后使用完成块来重置约束。

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

    view.layoutSubviews() 
    UIView.animate(withDuration: 0.9, animations: { 

     //something like this 
     self.animatableObject.origin.x -= 200 

    }, completion: {(finished: Bool) in 

     self.leadingConst.constant -= 200 

    }) 
} 

我不确定你想要什么动画,所以origin.x行只是一个例子。