How to synchronize my UILabel with system time?

I have a label in which I want to show the system time. And I want my label to be synchronized with it, i.e. The label will always be displayed at the same time as the time displayed in the status bar.

I set the label text to system time using this snippet:

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm"
label.text = formatter.stringFromDate(date)

But I do not know when to run this code. I thought I could run it every minute, but this does not always work. Consider this:

The user starts the application at the system time 08:00:30, this code starts. The time indicated on the status bar and the time indicated on my label are the same: 08:00

At system time 08:01:00, the time displayed in the status bar changes to 08:01. But since 1 minute has not passed since the application was launched, the text of the shortcut is still 08:00.

That's why I said that doing it every minute does not always work.

I also thought to use NSTimerto run this code every second or millisecond. But is it too excessive and cause performance problems?

Is there a “right” way to do this?

+4
source share
2 answers

, , 30 ( 08:00:30), 1 , ,

+3

u NSTimer 60 . , , ,

:

 func refreshTime(firstRefresh: Bool) {
    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "hh:mm"
    let time = formatter.stringFromDate(date)
    print(time)

    var interval = 60.0

    if firstRefresh{
        let formatter_second = NSDateFormatter()
        formatter_second.dateFormat = "ss"
        let second = formatter_second.stringFromDate(date)

        interval = 60 - Double(second)!
    }
    let _ = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: #selector(GameScene.refreshTime(_:)), userInfo: false, repeats: false)

}
0

Source: https://habr.com/ru/post/1653266/


All Articles