再次按下开始时定时器暂停按钮重置

timer pause button reseting when press start again

所以我有一个秒表程序,我的秒表正在工作,但是当我按下暂停按钮时,它会暂停,但是当我再次按下开始按钮以从它停止的地方启动秒表时,它会重置相反,我尝试了多种方法,但似乎没有任何效果,你能帮帮我吗? 下面是我的重置、启动和暂停功能代码,它们都是 IBactions 和 Outlets。

我认为问题出在开始或暂停按钮上

@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var pauseButton: UIButton!

@IBAction func startTimer(_ sender: AnyObject) {
    if(isPlaying) {
        return
    }
    startButton.isEnabled = false
    pauseButton.isEnabled = true
    isPlaying = true

    let aSelector : Selector = #selector(ViewController.updateTime)
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)

    counter = NSDate.timeIntervalSinceReferenceDate

}


@IBAction func pauseTimer(_ sender: AnyObject) {
    startButton.isEnabled = true
    pauseButton.isEnabled = false


    timer.invalidate()
    isPlaying = false

}

@IBAction func resetTimer(_ sender: AnyObject) {
    startButton.isEnabled = true
    pauseButton.isEnabled = false

    timer.invalidate()
    isPlaying = false
    counter = 0.0
    timeLabel.text = String("00:00:00:00")

}

然后我还有我的 Updatetimer 部分,我确定它可以正常工作,但如果你需要它,请问!!

如果您需要更多信息或规格,请询问或发表评论。

这是我的更新计时器

@objc func updateTime() { 让当前时间 = NSDate.timeIntervalSinceReferenceDate

    //Find the difference between current time and start time.
    var elapsedTime: TimeInterval = currentTime - counter

    //calculates the hour in elapsed time
    let hours = UInt8(elapsedTime / 3600.0)
    elapsedTime -= (TimeInterval(hours) * 3600.0)
    //calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (TimeInterval(minutes) * 60)

    //calculate the seconds in elapsed time.
    let seconds = UInt8(elapsedTime)
    elapsedTime -= TimeInterval(seconds)

    //find out the fraction of milliseconds to be displayed.
    let fraction = UInt8(elapsedTime * 100)

    //add the leading zero for minutes, seconds and millseconds and store them as string constants
    let strHours = String(format: "%02d", hours)
    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)
    let strFraction = String(format: "%02d", fraction)

    //concatenate minuets, seconds and milliseconds as assign it to the UILabel
    timeLabel.text = "\(strHours):\(strMinutes):\(strSeconds):\(strFraction)"
}

问题出在您的 startTimer() 函数中的这一行 counter = NSDate.timeIntervalSinceReferenceDate 中。如果 counter == 0.0,您应该只设置计数器。所以改变你的代码如下:

     if counter == 0.0{
          counter = NSDate.timeIntervalSinceReferenceDate

        }else{
          counter = previousDate.timeIntervalSinceReferenceDate

        }

还将以下行添加到您的暂停函数中,以便保存计数器暂停的日期,以便下次计数器从该点开始:

var previousDate = NSDate()
@IBAction func pauseTimer(_ sender: AnyObject){
//...Your other code...
previousDate = NSDate()
}

此外,您的 update 函数应该使用保存的日期 previousDate 来更新计数器。 这应该可以解决问题。