gpt4 book ai didi

swift - 如何等到计时器停止

转载 作者:行者123 更新时间:2023-11-28 06:15:52 24 4
gpt4 key购买 nike

我有一个包含 Timer 对象的可重用函数 countDown(seconds: Int)。函数 takeRest() 调用 countDown(seconds: Int) 函数,调用后立即打印:“test text”。我想做的是等待执行打印函数,直到 countDown(seconds: Int) 函数内的计时器停止执行并保持 countDown() 函数可重用。有什么建议吗?

private func takeRest(){
countDown(seconds: 10)
print("test text")
}

private func countDown(seconds: Int){
secondsToCount = seconds
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ [weak self] timer in
if (self?.secondsToCount)! > 0{
self?.secondsToCount -= 1
self?.timerDisplay.text = String((self?.secondsToCount)!)
}
else{
self?.timer.invalidate()
}
}
}
}

最佳答案

您可以在倒计时功能上使用闭包,请引用以下代码。

private func takeRest(){
countDown(seconds: 10) {
print("test text")
}
}

private func countDown(seconds: Int, then:@escaping ()->() ){
let secondsToCount = seconds
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ [weak self] timer in
if (self?.secondsToCount)! > 0{
self?.secondsToCount -= 1
self?.timerDisplay.text = String((self?.secondsToCount)!)

//call closure when your want to print the text.
//then()
}
else{
//call closure when your want to print the text.
then()
self?.timer.invalidate()
self?.timer = nil // You need to nil the timer to ensure timer has completely stopped.
}
}
}

关于swift - 如何等到计时器停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45162789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com