WKInterfaceTimer used as a timer to countdown start and stop

和自甴很熟 提交于 2019-12-03 13:57:16

Yes the watchkit timer is a bit...awkward...and definitely not very intuitive. But that's just my opinion

You'll have to keep setting the date/timer each time the user chooses to resume the timer.

Remember, you'll also need an internal NSTimer to keep track of things since the current WatchKit timer is simply for display without having any real logic attached to it.

So maybe something like this...It's not elegant. But it works

     @IBOutlet weak var WKTimer: WKInterfaceTimer! //watchkit timer that the user will see

        var myTimer : NSTimer?  //internal timer to keep track 
        var isPaused = false //flag to determine if it is paused or not
        var elapsedTime : NSTimeInterval = 0.0 //time that has passed between pause/resume
        var startTime = NSDate()
        var duration : NSTimeInterval = 45.0 //arbitrary number. 45 seconds

       override func willActivate(){
           super.willActivate()
           myTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false)
           WKTimer.setDate(NSDate(timeIntervalSinceNow: duration ))
            WKTimer.start()
       }

    @IBAction func pauseResumePressed() {
        //timer is paused. so unpause it and resume countdown
        if isPaused{
            isPaused = false
            myTimer = NSTimer.scheduledTimerWithTimeInterval(duration - elapsedTime, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false)
            WKTimer.setDate(NSDate(timeIntervalSinceNow: duration - elapsedTime))
            WKTimer.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.timeIntervalSinceDate(startTime)

                //stop watchkit timer on the screen
                WKTimer.stop()

                //stop the ticking of the internal timer
                myTimer!.invalidate()

                //do whatever UI changes you need to
                pauseResumeButton.setTitle("Resume")
            }
        }

      func timerDone(){
           //timer done counting down
      }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!