我正在写一个板球模拟器应用程序。我希望在循环中实现快速局,直到团队全力以赴。但是我想在每个球后稍微延迟,以便用户可以看到记分牌的更新。
以下是代码片段:
while (match.currentInnings == currentInnings)
{
playSingleBall()
if (gameover == true)
{
return
}
// Here's where I want the delay
}
playSingleBall做了大量的事情,包括大量的计算,然后在视图中写入大量的标签。但是,如果我将评论延迟(usleep或其他),标签根本不会更新。你能建议一些能让标签更新的东西吗?还是一种不会出现这种问题的延迟方法?
感谢。
答案 0 :(得分:1)
您可以使用Timer
类和重复处理程序:
// Every 20 sceonds
let interval: TimeInterval = 20
Timer(timeInterval: interval, repeats: true) { (timer) in
// Do what every you want to do (update the UI)
// Stop the loop when the game is over
if (gameover) {
timer.invalidate()
}
}
答案 1 :(得分:0)
我会将playSingleBall放在由另一个变量控制的if语句中。这个变量在playSingleBall的第一行被设置为false,然后只要playSingledBall的一个逻辑流到达它就会切换回true。
我还会考虑将playSingleBall分配给主要版本,因为它会更新UI。
像这样:
var singleBallBlocker : Bool = true
func playSingleBall() {
singleBallBlocker = false
// run the method...
// at some point.. wherever the function ends or returns you need to call:
singleBallBlocker = true
}
上面的代码无论你在哪里使用它:
while (match.currentInnings == currentInnings)
{
if singleBallBlocker
{
DispatchQueue.main.async(execute: {
playSingleBall()
}
}
if (gameover == true)
{
return
}
// Here's where I want the delay
}
当然,如果您不需要在方法内重置阻止程序,那么只需将其重置为您认为合适的地方。