2017-07-18 1 views
1

Ich habe eine wiederverwendbare Funktion countDown(seconds: Int), die Timer-Objekt enthält. Funktion takeRest() Anrufe countDown(seconds: Int) Funktion und nach dem Aufruf sofort druckt: "Text testen". Was ich tun möchte, ist mit der Ausführung der Druckfunktion zu warten, bis der Timer innerhalb der countDown(seconds: Int) Funktion stoppt ausgeführt und countDown() Funktion wiederverwendbar halten. Irgendwelche Vorschläge?Wie warten, bis der Timer stoppt

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() 
      } 
     } 
    } 
} 

Antwort

1

Sie können Schließung auf Countdown-Funktion verwenden, bitte folgenden Code als Referenz.

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

Ich denke, Sie wollen den 'then' Aufruf in der else-Klausel nach' timer.invalidate', so dass es ausgeführt wird, wenn der Timer beendet ist. – vacawama

+0

sicher, aber ich bin mir nicht bewusst, Bedingung, dass @ Barola_mes möchte, dass Text gedruckt wird. – dip