2017-07-01 9 views
0

現在、私は3 ... 2 ... 1 ...を作成しようとしています!カウントダウンのタイプはGoの直後です! Timer.scheduleTimerの完了ハンドラを使用するオプションは、私が理解しているものからカウントダウンする能力を持っていません。即時に完了ハンドラを使用してカウントダウンタイマーを作成する方法

現在のところ、私は3からカウントダウンできますが、Goでタイマーを無効にする方法はわかりません。アクションを実行する

var seconds = 3 
var countDownTimer = Timer() 

func startCountDown() { 
    countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TrackActivityVC.updateTimer), userInfo: nil, repeats: true) 
} 

func updateTimer() { 

    seconds -= 1 
    print(seconds) 
} 

// Not sure how to use this code to create a countdown, as it doesn't seem possible with this method 

Timer.scheduledTimer(withTimeInterval: someInterval, repeats: false) { 

} 

したがって、問題は完了ハンドラでカウントダウンタイマーを作る方法です。ここで

var seconds = 3 

Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in 
    self.seconds -= 1 
    if self.seconds == 0 { 
     print("Go!") 
     timer.invalidate() 
    } else { 
     print(self.seconds) 
    } 
} 

viewControllerがdeinitializedされたときにタイマーを無効に改良版である:ここで

答えて

3

は、末尾の閉鎖構文を使用して、カウントダウンタイマーを作成する方法です。それが閉じるとviewControllerにぶら下がるのを避けるために[weak self]を使用します。

class MyViewController: UIViewController { 
    var seconds = 3 
    var myTimer: Timer? 

    func startCountdown() { 
     myTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] timer in 
      self?.seconds -= 1 
      if self?.seconds == 0 { 
       print("Go!") 
       timer.invalidate() 
      } else if let seconds = self?.seconds { 
       print(seconds) 
      } 
     } 
    } 

    deinit { 
     // ViewController going away. Kill the timer. 
     myTimer?.invalidate() 
    } 
} 
+0

パーフェクトありがとう! – lifewithelliott

関連する問題