gpt4 book ai didi

ios - 将三个动画间隔一秒的最佳方法是什么?

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:29 24 4
gpt4 key购买 nike

有没有比使用 asyncAfter 三次更好的方法让这些动画间隔一秒?

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)

关于ios - 将三个动画间隔一秒的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48826350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com