Sync multiple time labels with host time

北战南征 提交于 2021-02-05 11:24:29

问题


What would be a possible way to update labels that displays static time received once from API.I have a tableView where each cell displays city name current temperature and time just like the native iPhone WeatherApp.Is there a way to observe the device clock minutes so I can trigger some code to update the times when a minute goes by?


回答1:


You can subclass a UILabel and add a timer to it so that it autoupdates itself:

Considering your last question where you get the timeZone offset from GMT from your API, you can subclass a UILabel, add a timeZone property to it and a didSet closure to setup a timer to fire at the next even minute with a 60 seconds interval and set it to repeat. Add a selector to update its label every time this method is called:

class Clock: UILabel {
    let dateFormatter = DateFormatter()
    var timer = Timer()
    var timeZone: Int = 0 {
        didSet {
            dateFormatter.timeStyle = .short
            dateFormatter.timeZone = TimeZone(secondsFromGMT: timeZone)
            var components = Date().components
            components.minute! += 1
            components.second = 0
            components.nanosecond = 0
            timer = .init(fireAt: components.date!, interval: 60, target: self, selector: #selector(update), userInfo: nil, repeats: true)
            RunLoop.main.add(timer, forMode: .common)
            update()
        }
    }
    @objc func update(_ timer: Timer? = nil) {
        text = dateFormatter.string(from: Date())
    }
}

extension Date {
    var components: DateComponents {
        Calendar.current.dateComponents(in: .current, from: self)
    }
}

Now you can just create your clock label and when you setup its timeZone property it will start running automatically:

let clock: Clock = .init(frame: .init(origin: .zero,
                                        size: .init(width: 200, height: 30)))
clock.timeZone = -14400

clock.text  // "11:01 PM"


来源:https://stackoverflow.com/questions/61298819/sync-multiple-time-labels-with-host-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!