如何在swift中使用完成处理程序进行倒计时

时间:2017-07-01 03:37:26

标签: ios swift timer

目前我正在尝试创建一个3 ... 2 ... 1 ... Go! 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) {

}

因此问题是如何使用完成处理程序使倒计时器。

1 个答案:

答案 0 :(得分:10)

以下是使用尾随闭包语法创建倒数计时器的方法:

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取消初始化时使计时器失效。它使用[weak self]来避免在viewController关闭时挂起:

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