![](/img/trans.png)
[英]Swift UIView animateWithDuration completion closure called immediately
[英]Swift animateWithDuration is completing immediately
这是我的代码,我立即获得打印输出。 我想在此期间更改uiview的backgroundcolor。
func animate() {
UIView.animateWithDuration(3.0, delay: 0.0, options:
UIViewAnimationOptions.CurveLinear, animations: {
//self.grid.backgroundColor = UIColor.redColor()
println("1")
UIView.animateWithDuration(1.0, delay: 1.0, options: UIViewAnimationOptions.CurveLinear, animations: {
//self.grid.backgroundColor = UIColor.clearColor()
println("2")
},
completion: {
(finished: Bool) - > Void in
println("3")
})
}, completion: {
(finished: Bool) - > Void in
println("4")
})
}
您要制作动画的东西是不能动画的。 通过检查您的代码,我了解到您正在尝试使视图透明。
您可以通过将视图的Alpha设为零来实现此目的。 (Alpha是可动画的)。
与红色相同。 尝试改用图层背景颜色
还要记住,animationWithDuration不会延迟值的分配,而是立即分配值
UIView.animateWithDuration(3.0, delay: 0.0, options:UIViewAnimationOptions.CurveLinear, animations: {
self.grid.layer.backgroundColor = UIColor.redColor().CGColor
UIView.animateWithDuration(1.0, delay: 1.0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.grid.alpha = 0
},
completion: {(finished: Bool) - > Void in})
}, completion: {(finished: Bool) - > Void in})}
几件事。 只有某些东西可以动画显示。 println()无法设置动画。
其次,尚不清楚将对UIView.animateWithDuration的调用嵌套在另一个对UIView.animateWithDuration的调用的动画块中的作用。
将对UIView.animateWithDuration的第二次调用嵌套在外部UIView.animateWithDuration调用的完成块中是合理的,但不能在动画块中嵌套。
MIGHT动画的代码已被注释掉,那么您希望完成什么?
这是一个IBAction方法,可将视图的背景颜色从白色变为红色,然后再变为白色。 它完美地工作:
@IBAction func handleAnimateButton(sender: UIButton)
{
sender.enabled = false
UIView.animateWithDuration(NSTimeInterval(0.2),
delay: NSTimeInterval(0.5),
options: UIViewAnimationOptions.CurveEaseInOut,
animations:
{
self.aView.backgroundColor = UIColor.redColor()
},
completion:
{
This code gets called when the first animation finished.
(value: Bool ) in
//Create a new animation to switch the BG color back to white
UIView.animateWithDuration(NSTimeInterval(0.5),
animations:
{
self.aView.backgroundColor = UIColor.whiteColor()
},
completion:
{
(value: Bool ) in
sender.enabled = true
}
)
}
)
}
请注意,第二个动画调用在第一个动画调用的完成块内。
我认为您遇到的问题是您在另一个选项中调用了animateWithDuration
选项并delay
调用。 这可能会破坏程序。 你应该解决这个问题。
希望有帮助:)
我不是专家,但是Duncan将第二个动画嵌套在第一个动画的完成块中的答案应该对您有用。 我必须删除最后的“ sender.enabled = true”片段才能使其正常工作。 就是说,如果任何读者的计时问题都不能解决,这是我已经阅读的其他选择...
使用NSTimeInterval: https : //developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/
或使用大型中央调度 (功能强大但复杂): http : //www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1
显然,iOS有一种新方法: http : //commandshift.co.uk/blog/2014/04/01/stop-nesting-animation-blocks/
同样,我认为可以通过完成块方法获得序列动画,但这是一些替代方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.