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

问题描述 投票:0回答:1

因此我有一个秒表程序,我有秒表正在工作,但是当我按下暂停按钮时,事情暂停但是当我再次按下启动按钮从它停止的地方启动秒表时它重置而不是我尝试了多个事情,但似乎没有什么工作可以帮助我。下面是我的重置,启动和暂停功能的代码,它们都是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(){let 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)"
}
swift4 nstimer xcode9
1个回答
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来更新计数器。这应该解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.