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