Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

ios - How can I make a countdown timer like in a music player?

I have a label and its value is "03:48".

I want to countdown it like a music player. How can I do that?

03:48 03:47 03:46 03:45 ... 00:00

var musictime =3:48

func stringFromTimeInterval(interval: NSTimeInterval) -> String {
    let interval = Int(interval)
    let seconds = interval % 60
    let minutes = (interval / 60)      
    return String(format: "%02d:%02d", minutes, seconds)
}

func startTimer() {
    var duration=musictime.componentsSeparatedByString(":")   //split 3  and 48

    var count = duration[0].toInt()! * 60 + duration[1].toInt()! //224 second

    timerCounter = NSTimeInterval( count )
    NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onTimer:", userInfo: nil, repeats: true)
}

@objc func onTimer(timer:NSTimer!) {
    // Here is the string containing the timer
    // Update your label here
    //println(stringFromTimeInterval(timerCounter))
    statusLabel.text=stringFromTimeInterval(timerCounter)

    timerCounter!--
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, by writing code. This is not a "Teach me how to program site. It's a site where you post questions about specific problems you are having with code you have written.

In short, though do the following:

Record your end time

let endInterval = NSDate.timeIntervalSinceReferenceDate() + secondsToEnd

Create a repeating timer that fires once/second.

Each time it fires, compute the number of seconds remaining to endInterval. Calculate minutes remaining as

Int((endInterval-nowInterval)/60)

Calculate seconds remaining as

Int(endInterval-nowInterval)%60

There is also the new (to iOS 8) class NSDateComponentsFormatter, which I've read a little about but haven't used. I believe that will generate formatted timer intervals like hh:mm:ss for you automatically. You'd use the same approach I outlined above, but instead of calculating minutes and seconds yourself, use the NSDateComponentsFormatter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...