我正在制作一个应用程序,用户可以同时启动多个计时器并在 ListView 中查看它们。
我知道有 2 个主要选项来计算时间:
- 从当前日期减去开始日期(当前日期-开始日期)
或
- 使用 NSTimer 并每秒从每个事件计时器中减去 1 秒。
我以前一直在使用后者,但在浏览互联网后,我开始认为数据型可能更好。
请告诉我您认为最好使用哪个,如果您选择第一个(日期),请提供一些示例代码来说明如何使用它。
最佳答案
您可以使用 NSTimer 并每秒从每个事件计时器中取出 1 秒。你可以使用这个类。
class CustomTimer {
typealias Update = (Int)->Void
var timer:Timer?
var count: Int = 0
var update: Update?
init(update:@escaping Update){
self.update = update
}
func start(){
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerUpdate), userInfo: nil, repeats: true)
}
func stop(){
if let timer = timer {
timer.invalidate()
}
}
/**
* This method must be in the public or scope
*/
@objc func timerUpdate() {
count += 1;
if let update = update {
update(count)
}
}
}
要使用多个计时器,您可以创建多个 CustomTimer 实例,示例代码:
let timer1 = CustomTimer { (seconds) in
// do whatever you want
}
timer1.start()
let timer2 = CustomTimer { (seconds) in
// do whatever you want
}
timer2.start()
注意:
timerUpdate 方法将以 1 秒的间隔准确调用。为了为函数执行保留一些空间,我们可以根据执行时间将间隔设置为 0.9 或 0.95。
关于ios - 多个计时器一次 ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48734508/