我有一个淡入顺序,依次为淡入和淡出。但是,代码的执行不会等到单个淡入淡出动画(fadeIn,fadeOut)结束后再执行。淡入完成后如何触发淡出?
到目前为止,这是我的基本代码:
func fadeIn(){
if self.alpha == 0.0 {
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 3.0,
delay: 2.0,
options:[.curveLinear],
animations: {self.alpha = 1.0},
completion: {if $0 == .end{print("FadeIn finished now")}})
}
}
func fadeOut(){
if self.alpha == 1.0 {
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 3.0,
delay: 2.0,
options:[.curveLinear],
animations: {self.alpha = 0},
completion: {if $0 == .end{print("FadeOut finished now")}})
}
}
//connect single Fades
func fadeSequence(){
self.fadeIn()
self.fadeOut()
}
问题是如何在执行进一步的代码之前将这些动画一个接一个地链接。
在我的应用程序中,我想实现一个重复循环,其中每个动画都必须在显示下一个动画之前完成:
for item in 0..<4{
print("runthrough:\(item)")
myView.fadeSequence()
}
我的基本问题是对完成部分的理解。
答案 0 :(得分:1)
您似乎在这里问了两个问题:
fadeOut
, fadeIn
完成后是?fadeSequence
结束之前再次调用?如果您总是想在运行fadeOut
之后直接调用fadeIn
,则可以执行以下操作:
func fadeIn(completion: @escaping () -> Void) {
guard alpha == 0 else { return }
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 3.0, delay: 2.0, options:[.curveLinear],
animations: {
self.alpha = 1.0
},
completion: {
self.fadeOut()
}
)
}
然后,fadeSequence
仅呼叫fadeIn()
。
但是,您可以更改逻辑来处理fadeSequence
内部的补全,这更加灵活,因为这样您就可以独立地调用fadeOut
:
func fadeIn(completion: @escaping () -> Void) {
guard alpha == 0 else { return }
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 3.0, delay: 2.0, options:[.curveLinear],
animations: {
self.alpha = 1.0
},
completion: completion
)
}
func fadeSequence() {
fadeIn(completion: fadeOut)
}
将完成处理程序添加到fadeSequence
,然后递归调用它。这也需要fadeOut
来实现完成处理程序,就像我们将其添加到fadeIn
一样。
func fadeSequence(numberOfCalls n: Int) {
guard n > 0 else { return }
fadeIn {
self.fadeOut {
fadeSequence(numberOfCalls: n-1)
}
}
}
完整代码:
func fadeIn(completion: @escaping () -> Void) {
guard alpha == 0 else { return completion() }
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 3.0, delay: 2.0, options:[.curveLinear],
animations: {
self.alpha = 1
},
completion: completion
)
}
func fadeOut(completion: @escaping () -> Void) {
guard alpha == 1 else { return completion() }
UIViewPropertyAnimator.runningPropertyAnimator(
withDuration: 3.0, delay: 2.0, options:[.curveLinear],
animations: {
self.alpha = 0
},
completion: completion
)
}
func fadeSequence(repeat n: Int = 1) {
guard n > 0 else { return }
fadeIn {
self.fadeOut {
fadeSequence(repeat: n-1)
}
}
}
someView.fadeSequence(repeat: 3)