实施的NSTimer在MVVM架构
问题描述:
我希望实现的NSTimer显示使用NSTimeInterval记时计,所以我环顾四周,发现这个代码,我把我的视图模型层:实施的NSTimer在MVVM架构
public class ViewModel {
public func startTimer() {
//if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
//}
}
@objc public func updateTime() -> String {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
//Find the difference between current time and start time.
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime/60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
//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)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
return "\(strMinutes):\(strSeconds)"
}
}
而且我想显示当前经过的时间对我的看法,所以试过,但没有奏效:
viewModel?.startTimer()
timerLabel.text = viewModel?.updateTime()
我如何能显示updateTime()
我的ViewController标签上的最新成果?
答
updateTime
方法不能只返回字符串。它必须启动有关标签的更新。您可以对其进行编码以直接更新标签,也可以提供updateTime
具有字符串值时调用的封闭。
答
我试图实现Rob的答案,但无法真正掌握MVVM架构中的CAdisplayLink,并提出了在不同视图中定期更新GUI元素的相同问题。 不过我用我的RAC的知识和创造,并通过一个RACSignal
更新我的ViewController:
RACSignal.interval(1.0, onScheduler: .mainThreadScheduler()).subscribeNext({ _ in
self.timerLabel.text = self.viewModel?.updateTime()
})
FWIW,没有必要运行计时器每0.01秒,当屏幕刷新封顶为60帧。我可能会建议一个'CADisplayLink'而不是'NSTimer'。另外,你可能想要使用'formatter.allowedUnits = [.Minute,.Second]','formatter.unitsStyle = .Positional'的'NSDateComponentsFormatter',而不是自己计算经过的时间并构建字符串,和'formatter.zeroFormattingBehavior = .Pad'。然后,要更新定时器/显示链接处理程序中的标签,它只是'timerLabel.text = formatter.stringFromDate(startDate,toDate:NSDate())'。 – Rob