使用 NSTimer 仅以秒为单位倒计时(从 00:20 到 0)

2023-12-15

我需要一个从 20 秒到 0 的标签倒计时,然后重新开始。这是我第一次用 Swift 做一个项目,我正在尝试使用NSTimer.scheduledTimerWithTimeInterval。此倒计时应循环运行给定的次数。

我很难实施Start and 重新开始方法(循环)。我基本上没有找到一种方法来启动 20 秒的时钟,当它结束时,再次启动它。

如果有任何关于如何做到这一点的想法,我将不胜感激 瓦格纳

 @IBAction func startWorkout(sender: AnyObject) {

    timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("countDownTime"), userInfo: nil, repeats: true)
    startTime = NSDate.timeIntervalSinceReferenceDate()

}

func countDownTime() {

    var currentTime = NSDate.timeIntervalSinceReferenceDate()

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

    //calculate the seconds in elapsed time.
    let seconds = UInt8(elapsedTime)
    elapsedTime -= NSTimeInterval(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 strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
    let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)

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

您应该将日期 endTime 设置为从现在起 20 秒,然后检查日期 timeIntervalSinceNow。一旦 timeInterval 达到 0,您可以从现在起再次将其设置为 20 秒

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var strTimer: UILabel!

    var endTime = Date(timeIntervalSinceNow: 20)
    var timer = Timer()

    @objc func updateTimer(_ timer: Timer) {
        let remaining = endTime.timeIntervalSinceNow
        strTimer.text = remaining.time
        if remaining <= 0 {
            endTime += 20
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        strTimer.font = .monospacedSystemFont(ofSize: 20, weight: .semibold)
        strTimer.text =  "20:00"
        timer = .scheduledTimer(timeInterval: 1/30, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }

}

extension TimeInterval {
    var time: String {
        String(format: "%02d:%02d", Int(truncatingRemainder(dividingBy: 60)), Int((self * 100).truncatingRemainder(dividingBy: 100)))
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 NSTimer 仅以秒为单位倒计时(从 00:20 到 0) 的相关文章

随机推荐