延迟循环调用动画过程

时间:2020-07-02 09:01:42

标签: swift xcode delay

这是我代码的一部分,我在这里尝试延迟名为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])
    }
}

2 个答案:

答案 0 :(得分:1)

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

useBuiltIns: "usage"

重构

尝试不按索引调用数组元素:

for x in 1...players {
   //drop the name in from the top of the screen
   delay(2.0 * x) {
   self.dropText(playing[x-1])
}

答案 1 :(得分:0)

看看循环。您几乎立即接连打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])
    }
}