我有一个包含Timer对象的可重用函数countDown(seconds: Int)
。函数takeRest()
调用countDown(seconds: Int)
函数,调用后立即打印:“test text”。我想做的是等待执行print函数,直到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()
}
}
}
}
答案 0 :(得分:1)
您可以在倒计时功能上使用闭包,请参考以下代码以供参考。
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.
}
}
}