gpt4 book ai didi

ios - 如何制作像音乐播放器一样的倒计时器?

转载 作者:行者123 更新时间:2023-11-30 14:02:30 25 4
gpt4 key购买 nike

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

我想像音乐播放器一样倒计时。我怎样才能做到这一点?

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 方法 dateByAddingTimeInterval 将 future 日期设置为 endDate如下:

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

关于ios - 如何制作像音乐播放器一样的倒计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com