我正在使用这段代码在 NSLabel 中显示时间:
模型
func startClock() {
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(fireAction), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: RunLoop.Mode.common)
timer?.tolerance = 0.05
fireAction()
}
@objc dynamic func fireAction() {
delegate?.timeToUpdateClock(self)
}
视图控制器
extension ViewController: ClockWorksProtocol {
func timeToUpdateClock(_ timer: ClockWorks) {
tick()
}
}
func tick() {
clockDateLabel.stringValue = DateFormatter.localizedString(from: Date(), dateStyle: .full, timeStyle: .none)
clockTimeLabel.stringValue = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium)
}
一切似乎都很正常,但不幸的是显示的秒数与菜单栏上时钟所看到的秒数不同步。我认为这是因为我每秒更新一次时钟,但用户没有在正确的时间点击开始,而是在一个随意的间隔内从一秒到下一秒(我使用1.0的计时器时间间隔)。
我可以将计时器的时间间隔从1.0秒更改为0.1秒。这似乎有效,但我担心这会消耗过多的资源。
我发布了两张同时拍摄的屏幕截图。它们显示不同的时间(秒数)。
我该如何解决这个间隙?
Date()
是时钟上的时间。它就是现在,简单明了。 - matt