我目前正在为 Apple Watch 制作秒表。手表有两个接口和两个控制器。TimerController
和SwitchController
。TimerController
运行计时器。我正在尝试从 中停止时间对象,SwitchController
因此制作了一个函数来停止我的计时器,我TimerController
可以在SwitchController
. 问题是我得到了一个致命的错误TimerController
,我不知道为什么?
timeStopp()
中的函数timerController
返回错误:
“线程 1:致命错误:在展开可选值时意外发现 nil”
看到这张图片!
错误
SwipeController 滑动错误
TimeController 时间错误 1 时间错误 2
FrameWork 我在这里输入吗?
定时器控制器
import WatchKit
import Foundation
class TimerController: WKInterfaceController {
@IBOutlet weak var timerOutlet: WKInterfaceTimer!
var myTimer : Timer?
var duration : TimeInterval = 45.0 //arbitrary number. 45 seconds
var isPaused = false //flag to determine if it is paused or not
var elapsedTime : TimeInterval = 0.0 //time that has passed between
pause/resume
var startTime = NSDate()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
start_timer()
timerOutlet.setTextColor(UIColor.red)
// Configure interface objects here.
}
func start_timer() {
myTimer = Timer.scheduledTimer(timeInterval: duration, target:
self,selector: Selector(("timerDone")), userInfo: nil, repeats:
false)
timerOutlet.setDate(NSDate(timeIntervalSinceNow: duration ) as
Date)
timerOutlet.start()
}
func timerDone(){
//timer done counting down
}
@IBAction func pauseResumePressed() {
//timer is paused. so unpause it and resume countdown
if isPaused{
isPaused = false
myTimer = Timer.scheduledTimer(timeInterval: duration -
elapsedTime, target: self, selector:
Selector(("timerDone")), userInfo:
nil, repeats: false)
timerOutlet.setDate(NSDate(timeIntervalSinceNow: duration -
elapsedTime) as Date)
timerOutlet.start()
startTime = NSDate()
//pauseResumeButton.setTitle("Pause")
}
//pause the timer
else{
isPaused = true
//get how much time has passed before they paused it
let paused = NSDate()
elapsedTime += paused.timeIntervalSince(startTime as Date)
//stop watchkit timer on the screen
timerOutlet.stop()
//stop the ticking of the internal timer
myTimer!.invalidate()
//do whatever UI changes you need to
//pauseResumeButton.setTitle("Resume")
}
}
override func willActivate() {
// This method is called when watch view controller is about to
be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no
longer visible
super.didDeactivate()
}
}
更新的SwipeController
import WatchKit
import Foundation
class SwipeController: WKInterfaceController {
//@IBOutlet weak var myTimer: WKInterfaceTimer!
var timer = TimerController()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to
be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no
longer visible
super.didDeactivate()
}
/stopp call is made here
@IBAction func PauseButton() {
timer.pauseResumePressed()
}
}