开始,暂停,恢复NSTimer Swift

时间:2016-08-31 12:49:07

标签: swift2 nstimer

我想创建一个倒数计时器功能,用户可以按下相同的按钮暂停和恢复。我知道在SO上有几个类似的问题,包括one回答。但是,我仍然坚持(第二天)。尽管失效了,我的计时器似乎还在滴答作响。

这是我的代码:

@IBOutlet weak var timerLabel: UILabel!
var duration: NSTimeInterval { return Double((exercise!.duration))! * 60 }
var interval: Double?
var timer = NSTimer()
var startTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: Double?
var timeLeft: Double?
var inProgress = false
var isPaused = false
var completionStatus = false


@IBAction func pressStart(sender: UIButton) {
    if inProgress{
        if isPaused {
            resumeAnimation(timeLeftShapeLayer)
            sender.setTitle("Pause", forState: UIControlState.Normal)
            print("pressed resume, with \(timeLeft!) time left")
            startTime = NSDate.timeIntervalSinceReferenceDate()
            timer = NSTimer.scheduledTimerWithTimeInterval(timeLeft!, target: self, selector: #selector(PerformExerciseViewController.updateTime), userInfo: nil, repeats: false)
            isPaused = false

        } else {
            pauseAnimation(timeLeftShapeLayer)
            isPaused = true
            sender.setTitle("Resume", forState: UIControlState.Normal)

            elapsedTime = NSDate.timeIntervalSinceReferenceDate() - startTime
            timeLeft = duration - elapsedTime!
            timer.invalidate()

            print("pressed pause, with \(timeLeft!) time left")
        }
    } else {
        drawTimeLeftShape()
        timeLeftShapeLayer.addAnimation(strokeIt, forKey: nil)
        sender.setTitle("Pause", forState: UIControlState.Normal)

        startTime = NSDate.timeIntervalSinceReferenceDate()
        timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: #selector(PerformExerciseViewController.updateTime), userInfo: nil, repeats: false)
        inProgress = true
        isPaused = false
    }

打印时间:

按下暂停,剩下56.3997309803963时间(此处长时间暂停,可能是10秒)

按下简历,剩余时间为56.3997309803963(超短暂播放时间0.1秒)

按下暂停,剩下47.3651859760284时间(似乎是在暂停期间计算的时间

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

我计算错误的剩余时间。 而不是:

timeLeft = duration! - elapsedTime!

使用:

timeLeft = timeLeft! - elapsedTime!