2017-07-18 73 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