2017-07-18 118 views
1

我有一个包含Timer对象的可重用函数countDown(seconds: Int)。功能takeRest()调用countDown(seconds: Int)函数并在调用后立即打印:“测试文本”。我想要做的是等待执行打印功能,直到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() 
      } 
     } 
    } 
} 

回答

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. 
     } 
    } 
} 
+0

我想你想在'timer.invalidate'之后的else子句中调用'then',这样它在定时器完成时执行。 – vacawama

+0

当然,但我不知道@barola_mes想要打印文本的情况。 – dip