使用 Swift 在 WatchOS 中创建一个简单的计时器 4

Creating a simple timer in WatchOS with Swift 4

看似简单,但我正在努力...下面的代码在设置 workoutTimer 日期的行上崩溃。另外,我的 WKInterfaceTimer 没有连接到 IBOutlet,是否需要连接?我只是为了当时的目的而使用它。

class InterfaceController { 
            var workoutTimer: WKInterfaceTimer!
            var workoutStartTime: NSDate? = nil

    func startWorkOutTimer() {
   self.startWorkout()
            if let test = self.workoutSecondsElapsed() {
            print("timer seconds = \(test)")
            }
}


    func startWorkout() {
        // To count up use 0.0 or less, otherwise the timer counts down.
        workoutTimer.setDate(NSDate(timeIntervalSinceNow: 0.0) as Date)
        workoutTimer.start()
        self.workoutStartTime = NSDate()
    }

    func stopWorkout() {
        workoutTimer.stop()
    }

    func workoutSecondsElapsed() -> TimeInterval? {
        // If the timer hasn't been started then return nil
        guard let startTime = self.workoutStartTime else {
            return nil
        }
        // Time intervals from past dates are negative, so
        // multiply by -1 to get the elapsed time.
        return -1.0 * (self.workoutStartTime?.timeIntervalSinceNow)!
    }

}

来自 Apple 文档:

Do not subclass or create instances of this class yourself. Instead, define outlets in your interface controller class and connect them to the corresponding objects in your storyboard file.

您的应用程序可能正在崩溃,因为您的计时器为零,但是您可以根据需要使用计时器 class 而不是 WKInterfaceTimer。