有没有比使用asyncAfter
3 次更好的方法将这些动画间隔一秒?
let firstAnimationTime = DispatchTime.now()
let secondAnimationTime = DispatchTime.now() + 1
let thirdAnimationTime = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: firstAnimationTime) {
self.firstAnimation()
}
DispatchQueue.main.asyncAfter(deadline: secondAnimationTime) {
self.secondAnimation()
}
DispatchQueue.main.asyncAfter(deadline: thirdAnimationTime) {
self.thirdAnimation()
}
您可以使用 UIView.animate(withDuration:delay:...)
甚至可以定义一个函数如下:
func animateSequentially(withDurations durations: [TimeInterval], animations: [(() -> Void)]) {
guard durations.count == animations.count else {
return
}
for index in 0..<animations.count {
// calculate delay
let delay: TimeInterval = durations[0..<index].reduce(TimeInterval(0), { delay, duration in
return delay + duration
})
// perform animation
UIView.animate(withDuration: durations[index],
delay: delay,
options: [],
animations: animations[index],
completion: nil)
}
}
并像这样使用:
let myView = UIView()
let durations = [1, 0.5, 1.25]
let animations = [{ myView.backgroundColor = .red },
{ myView.backgroundColor = .yellow },
{ myView.backgroundColor = .blue }]
animateSequentially(withDurations: durations, animations: animations)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句