再次按下开始时,定时器暂停按钮复位

时间:2018-09-16 21:37:04

标签: swift4 nstimer xcode9

所以我有一个秒表程序,并且我的秒表正在工作,但是当我按下暂停按钮时,事情暂停了,但是当我再次按下开始按钮以从秒表停止的地方开始时,它复位了,已经尝试了多种方法,但似乎无济于事,您可以帮我吗。 下面是我用于重置,启动和暂停功能的代码,它们都是IBaction和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(){         让currentTime = 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)"
}

1 个答案:

答案 0 :(得分:0)

问题出在counter = NSDate.timeIntervalSinceReferenceDate函数的startTimer()行中。您仅应将计数器设置为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更新计数器。 那应该可以解决问题。