在循环中使用 dispatchQueue [英] Using dispatchQueue in loops

查看:62
本文介绍了在循环中使用 dispatchQueue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试延迟循环一些东西(作为概念证明)这是为了别的东西.但为了简化,这里有一个例子.

I am attempting to loop something with a delay (just as a proof of concept) this is for something else. But to simplify it, here is an example.

所以在这个例子中,我有一个带有text"的字符串,我想循环添加另一个字符串,比如 10 次.唯一的问题是我希望每次迭代都有延迟.到目前为止,这是我的代码.

so in this example, I have a string with "text" and I want to loop the addition of another string lets say 10 times. The only thing is that I want there to be a delay in each iteration. here is my code thus far.

//全局变量

var myString = "text"

var myString = "text"

//按钮内的动作

    let delayInSeconds = 1.0
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {

        for _ in 1...10 {
           self.myString += "another text"
        }
    }
    labelOne.text = myString

}

我应该补充一点,结果是立即添加了所有 10 个另一个文本",没有任何延迟.

I should add that the result is that all 10 "another text" are added immediately without any delay.

谢谢

推荐答案

在您的示例中,您在同一个工作单元中附加了十次字符串.尝试每个循环分派一次工作:

In your example, you append your string ten times in the same work unit. Try dispatching work once per loop:

for delay in 1...10 {
    let delayInSeconds = Double(delay)
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
        self.myString += "another text"
        labelOne.text = myString
    }
}

不过,这个循环不适用于任意大的值.它也没有提供我们可能需要的用户界面更改的精确时间.为此,我们可以使用 Timer.这是使用 Timer 重新处理的相同问题:

This loop won't work well for arbitrarily large values, though. It also doesn't provide the kind of precise timing we might want for user interface changes. For that, we can use Timer. Here’s the same problem reworked with Timer:

// Add to the class body…
var i = 1
// Lazy initialization so the timer isn’t initialized until we call it
lazy var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {timer in
    guard self.i <= 20 else {
        timer.invalidate()
        return
    }

    self.label.text?.append(" another text")
    self.i += 1
}

// Add to the button action…
timer.fire()

这篇关于在循环中使用 dispatchQueue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆