首页 > 解决方案 > 延迟循环调用动画流程

问题描述

这是我的代码的一部分,我试图延迟一个名为的函数,该函数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])
    }
}

标签: swiftxcodedelay

解决方案


这个问题是因为你同时延迟了所有这些!您应该尝试为每个分配不同的延迟时间:

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)
}

推荐阅读