代码之家  ›  专栏  ›  技术社区  ›  GarySabo

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

  •  1
  • GarySabo  · 技术社区  · 7 年前

    看起来很简单,但我正在努力。。。下面的代码在设置workoutTimer日期的行上崩溃。另外,我的WKInterfaceTimer没有连接到IBMoutlet,它需要连接吗?我想用它只是为了时间的目的。

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

    }

    1 回复  |  直到 7 年前
        1
  •  1
  •   Francesco Deliro    7 年前

    从…起 苹果文档:

    你的应用程序可能会崩溃,因为你的计时器为零,但为了满足你的需要,你可以使用timer类而不是WKInterfaceTimer。