与主机时间同步多个时间标签 [英] Sync multiple time labels with host time

查看:41
本文介绍了与主机时间同步多个时间标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么可能的方法来更新显示从API接收到的静态时间的标签.我有一个 tableView ,其中每个 cell 仅显示城市名称当前的温度和时间像原生的iPhone WeatherApp一样,是否有办法观察设备的时钟分钟,以便我可以触发一些代码来更新分钟的时间?

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?

推荐答案

您可以将UILabel子类化,并向其中添加一个计时器,以使其自动更新:

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

考虑最后一个问题,即从API中获取GMT的timeZone偏移量,您可以将UILabel子类化,向其中添加timeZone属性,并添加didSet闭包以设置计时器以在60秒内的下一分钟触发间隔并将其设置为重复.每次调用此方法时,添加一个选择器以更新其标签:

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)
    }
}


现在,您只需创建时钟标签,并在设置其timeZone属性时,它将自动开始运行:


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"

这篇关于与主机时间同步多个时间标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆