Stopwatch using NSTimer incorrectly includes paused time in display

后端 未结 5 1309
盖世英雄少女心
盖世英雄少女心 2020-12-06 08:34

This is my code for an iPhone stopwatch. It works as expected and stops and resumes when the buttons are clicked.

When I hit \"Stop\", however, the timer won\'t st

5条回答
  •  情话喂你
    2020-12-06 08:51

    A timer class I created in Swift for a timer program in which a counter is updated every second from a set time. Answered to illustrate the Swift solution and the NSTimer function.

    The timer can be stopped and restarted; it will resume from where it stopped. Events can be intercepted by the delegate for start, stop, reset, end and second events. Just check the code.

    import Foundation
    
    protocol TimerDelegate {
      func didStart()
      func didStop()
      func didReset()
      func didEnd()
      func updateSecond(timeToGo: NSTimeInterval)
    }
    
    // Inherit from NSObject to workaround Selector bug
    class Timer : NSObject {
    
      var delegate: TimerDelegate?
      var defaultDuration: NSTimeInterval?
    
      var isRunning: Bool {
        get {
          return self.timer != nil && timer!.valid
        }
      }
    
      private var secondsToGo: NSTimeInterval = 0
    
      private var timer: NSTimer?
    
      init(defaultDuration: NSTimeInterval, delegate: TimerDelegate? = nil) {
        self.defaultDuration = defaultDuration
        self.delegate = delegate
        super.init()
      }
    
      func start() {
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
        self.timer!.tolerance = 0.05
    
        if delegate != nil { delegate!.didStart() }
      }
    
      func stop () {
        self.timer?.invalidate()
        self.timer = nil
    
        if delegate != nil { delegate!.didStop() }
      }
    
      func reset() {
        self.secondsToGo = self.defaultDuration!
    
        if delegate != nil { delegate!.didReset() }
      }
    
    
      func updateTimer() {
        --self.secondsToGo
        if delegate != nil { delegate!.updateSecond(self.secondsToGo) }
    
        if self.secondsToGo == 0 {
          self.stop()
          if delegate != nil { delegate!.didEnd() }
        }
      }
    
    }
    

提交回复
热议问题