Вы можете создать подкласс UILabel и добавить к нему таймер, чтобы он автоматически обновлялся:
Учитывая ваш последний вопрос, где вы получаете смещение timeZone от GMT из вашего API, вы можете создать подкласс UILabel, добавить свойство timeZone и замыкание didSet для установки таймера на следующую четную минуту с интервалом в 60 секунд и его повторения. Добавьте селектор, чтобы обновлять свою метку каждый раз, когда вызывается этот метод:
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 она запустится работает автоматически:
let clock: Clock = .init(frame: .init(origin: .zero,
size: .init(width: 200, height: 30)))
clock.timeZone = -14400
clock.text // "11:01 PM"