如何在音乐播放器中制作倒数计时器? [英] How can I make a countdown timer like in a music player?

查看:273
本文介绍了如何在音乐播放器中制作倒数计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签,其值为03:48。

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

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!--
}


推荐答案

你应该看看NSDate属性 timeIntervalSinceNow 。您所需要的只是使用NSDate方法将未来日期设置为endDate dateByAddingTimeInterval 如下:

You should take a look at NSDate property timeIntervalSinceNow. All you need is to set a future date as the endDate using NSDate method dateByAddingTimeInterval as follow:

class ViewController: UIViewController {

    @IBOutlet weak var timerLabel: UILabel!

    var remainingTime: NSTimeInterval = 0
    var endDate: NSDate!
    var timer = NSTimer()

    override func viewDidLoad() {
        super.viewDidLoad()
        remainingTime = 228.0   // choose as many seconds as you want (total time)
        endDate = NSDate().dateByAddingTimeInterval(remainingTime)   // set your future end date by adding the time for your timer

        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateLabel", userInfo: nil, repeats: true)  // create a timer to update your label
    }
    func updateLabel() {
        timerLabel.text = endDate.timeIntervalSinceNow.mmss
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

// you will need this extension to convert your time interval to a time string

extension NSTimeInterval {
    var mmss: String {
        return self < 0 ? "00:00" : String(format:"%02d:%02d", Int((self/60.0)%60), Int(self % 60))
    }
    var hmmss: String {
        return String(format:"%d:%02d:%02d", Int(self/3600.0), Int(self / 60.0 % 60), Int(self % 60))
    }
}

这篇关于如何在音乐播放器中制作倒数计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆