延时循环调用动画过程
Delay loop calling animation process
这是我的一段代码,我在其中尝试延迟一个名为 dropText
的函数,该函数从屏幕顶部删除一个名称。我尝试使用延迟功能,但它会延迟然后立即将它们全部删除。我错过了什么,或者这种方法完全错误?提前致谢:
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
//New group choose method
func groupChoose()
{
//loop through the players
for x in 0...players - 1{
//drop the name in from the top of the screen
delay(2.0) {
self.dropText(playing[x])
}
}
这个问题是因为你一次拖延了所有的人!您应该尝试为每个分配不同的延迟时间:
for x in 1...players {
//drop the name in from the top of the screen
delay(2.0 * x) {
self.dropText(playing[x-1])
}
重构
尽量不要按索引调用数组元素:
for playing in playing.enumerated() {
// drop the name in from the top of the screen
let player = playing.offset + 1
delay(2.0 * player) {
self.dropText(playing.element)
}
看看循环。您几乎立即一个接一个地呼叫 asyncAfter
。所以文本在延迟后 几乎立即一个接一个 也被丢弃。
我建议使用 Timer
func delay(_ delay: Double, numberOfIterations: Int, closure:@escaping (Int) -> Void) {
var counter = 0
Timer.scheduledTimer(withTimeInterval: delay, repeats: true) { timer in
DispatchQueue.main.async { closure(counter-1) }
counter += 1
if counter == numberOfIterations { timer.invalidate() }
}
}
和
func groupChoose()
{
delay(2.0, numberOfIterations: players) { counter in
self.dropText(playing[counter])
}
}
这是我的一段代码,我在其中尝试延迟一个名为 dropText
的函数,该函数从屏幕顶部删除一个名称。我尝试使用延迟功能,但它会延迟然后立即将它们全部删除。我错过了什么,或者这种方法完全错误?提前致谢:
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
//New group choose method
func groupChoose()
{
//loop through the players
for x in 0...players - 1{
//drop the name in from the top of the screen
delay(2.0) {
self.dropText(playing[x])
}
}
这个问题是因为你一次拖延了所有的人!您应该尝试为每个分配不同的延迟时间:
for x in 1...players {
//drop the name in from the top of the screen
delay(2.0 * x) {
self.dropText(playing[x-1])
}
重构
尽量不要按索引调用数组元素:
for playing in playing.enumerated() {
// drop the name in from the top of the screen
let player = playing.offset + 1
delay(2.0 * player) {
self.dropText(playing.element)
}
看看循环。您几乎立即一个接一个地呼叫 asyncAfter
。所以文本在延迟后 几乎立即一个接一个 也被丢弃。
我建议使用 Timer
func delay(_ delay: Double, numberOfIterations: Int, closure:@escaping (Int) -> Void) {
var counter = 0
Timer.scheduledTimer(withTimeInterval: delay, repeats: true) { timer in
DispatchQueue.main.async { closure(counter-1) }
counter += 1
if counter == numberOfIterations { timer.invalidate() }
}
}
和
func groupChoose()
{
delay(2.0, numberOfIterations: players) { counter in
self.dropText(playing[counter])
}
}