在Swift中恢复NSTimer

时间:2016-01-07 01:57:44

标签: ios swift swift2 nstimer

我在这方面看到的其他问题没有帮助。我希望能够启动,暂停,然后恢复NSTimer。我知道如何启动NSTimer。我也知道你不能暂停' NSTimer但你可以使它无效。但是,如果我想在恢复计时器的同时恢复它,我该怎么办呢?这是代码:

var startTimer = NSTimeInterval()
var timer = NSTimer()
@IBOutlet var displaylabel: UILabel! 
@IBAction func start(sender: UIButton) {
        timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
        startTimer = NSDate.timeIntervalSinceReferenceDate()
}
@IBAction func stop(sender: UIButton) {
timer.invalidate()
}
@IBAction func resume(sender: UIButton) {
// Code needed
}
func updateTime() {
    let currentTime = NSDate.timeIntervalSinceReferenceDate()
    var elapsedTime: NSTimeInterval = currentTime - startTimer
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (NSTimeInterval(minutes) * 60)
    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(seconds)
    let fraction = UInt8(elapsedTime * 100)
    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)
    let strFraction = String(format: "%02d", fraction)
    displaylabel.text = "\(strMinutes):\(strSeconds).\(strFraction)"
}

提前致谢。安东

1 个答案:

答案 0 :(得分:2)

您应该使用CADisplayLink有两个原因:

  1. 您将尽可能频繁地更新屏幕,而不是浪费额外的电池寿命,试图更频繁地更新它。所有iOS设备(在极少数情况下除了iPad Pro)每秒最多更新屏幕60次。将计时器安排0.01秒意味着您尝试每秒至少更新屏幕40次。

  2. 您可以暂停和恢复CADisplayLink

  3. 处理暂停需要一点思考。你想要做的是记录你暂停的时间(与开始时间不同),然后当你恢复时,将开始时间增加到暂停后经过的时间。

    class ViewController: UIViewController {
    
        private var startTime = NSTimeInterval(0)
        private var pauseTime = NSTimeInterval(0)
        private var displayLink: CADisplayLink!
    
        @IBOutlet var label: UILabel!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            displayLink = CADisplayLink(target: self, selector: "displayLinkDidFire")
            displayLink.paused = true
            displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
        }
    
        @IBAction func startWasTapped(sender: AnyObject) {
            startTime = NSDate.timeIntervalSinceReferenceDate()
            displayLink.paused = false
        }
    
        @IBAction func resumeWasTapped(sender: AnyObject) {
            startTime += NSDate.timeIntervalSinceReferenceDate() - pauseTime
            displayLink.paused = false
        }
    
        @IBAction func stopWasTapped(sender: AnyObject) {
            pauseTime = NSDate.timeIntervalSinceReferenceDate()
            displayLink.paused = true
        }
    
        func displayLinkDidFire() {
            let elapsedTime = NSDate.timeIntervalSinceReferenceDate() - startTime
            label.text = String(format: "%02.0f:%05.2f", floor(elapsedTime / 60), elapsedTime)
        }
    
    }