使用Time Interval Class的iOS倒计时器

时间:2016-12-08 16:35:58

标签: ios swift timer stopwatch

我使用以下算法进行秒表观察。但我需要的是使用TimeInterval类从特定给定时间倒计时的计时器,所以我需要稍微调整一下这段代码才能实现我需要的功能。任何帮助将不胜感激。

Here is the link of the tutorial.

@IBAction func start(sender: AnyObject) {
    let aSelector : Selector = “updateTime”
    timeTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ViewController.updateTime), userInfo: nil, repeats: true)

    startTime = Date.timeIntervalSinceReferenceDate
}   

var startTime = TimeInterval()
var timeTimer = Timer()

func updateTime() {
    //let currentTime = date.parseDuration(timeString: "\(displayTimeLabel.text)")
    let currentTime = Date.timeIntervalSinceReferenceDate

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

    //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 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
    displayTimeLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
}

这是我试图做的事情:

我使用扩展程序将String解析为TimeInterval

    extension Date {

    func parseDuration(timeString:String) -> TimeInterval {

        guard !timeString.isEmpty else {
            return 0
        }

        var interval:Double = 0

        let parts = timeString.components(separatedBy:":")
        for (index, part) in parts.reversed().enumerated() {
            interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
        }

        return interval
    }
}

然后添加了我需要的开始和结束时间。但输出不正确。我每次都从显示屏上获取当前时间。

let constTimeString = "15:04:46"

var date = Date()

var startTime = TimeInterval()
var timeTimer = Timer()

    func updateTimeAction() {

        timeTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(ViewController.updateTime2), userInfo: nil, repeats: true)
        startTime = date.parseDuration(timeString: constTimeString)

    }

func updateTime2() {

         let currentTime = date.parseDuration(timeString: displayTimeLabel.text!)
        var elapsedTime: TimeInterval = currentTime - startTime
        print("elapsed: \(elapsedTime)")


        //calculate the minutes in elapsed time.

        let minutes = Int(elapsedTime / 60.0)
        print("minutes: \(minutes)")
        elapsedTime -= (TimeInterval(minutes) * 60)

        //calculate the seconds in elapsed time.

        let seconds = Int(elapsedTime)
        print("seconds: \(seconds)")
        elapsedTime -= TimeInterval(seconds)

        //find out the fraction of milliseconds to be displayed.

        let fraction = Int(elapsedTime * 100)
        print("fraction \(fraction)")
        //add the leading zero for minutes, seconds and millseconds and store them as string constants

        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

        displayTimeLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)"
    }

1 个答案:

答案 0 :(得分:0)

你的错误在这里:

let currentTime = date.parseDuration(timeString: displayTimeLabel.text!)
var elapsedTime: TimeInterval = currentTime - startTime

根本不要获取displayTimeLabel.text的值。它是 view ,而不是 model 。你唯一应该做的就是设置它。在幕后跟踪模型(您正在操作的数据)。

好的,那就回到原来的样子吧。记录开始计数的开始时间,并将当前时间用作当前时间,然后减去以了解已经过了多长时间:

let currentTime = Date.timeIntervalSinceReferenceDate
var elapsedTime: TimeInterval = currentTime - startTime

好的,现在你知道从constTimeString中减去多少经过的时间(解析成一个时间间隔)来了解displayTimeLabel.text中现在显示的时间字符串。