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

标签 ios swift timer nstimer watchos

看似简单,但我正在努力...下面的代码在设置 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.

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

关于ios - 使用 Swift 4 在 WatchOS 中创建一个简单的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47146516/

相关文章:

javascript - 单击按钮永久删除计时器

objective-c - 使用 Accelerate Framework 的 iOS 的 FFT 音调检测?

objective-c - 谷歌地图将被取代?是真的吗?

javascript - zIndex 在 IOS 的 react-native 中无法正常工作

ios - 即使更新应用程序图标,共享扩展的应用程序图标也不会在设备中更新

Swift5 CoreStore CoreStore.fetchAll() 抛出错误

swift - 我什么时候以及为什么要在 Swift 中使用协议(protocol)?

ios - SCNNode childNodes 的总高度

java - 如何消除更改标签中显示的图像之间的闪烁?

android - 终止 Activity 后计时器的生命周期