本文介绍了Swift - 显示时间的更新/刷新标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个标签,以12小时格式显示当前时间。
I have a label which displays the current time in 12-hour format.
但是,每次分钟/小时更改时,它都不会更新/刷新时间。
But, it does not update/refresh the time every time the minute/hour changes.
我需要它在时间变化时自动将标签更改为当前时间。
I need it to automatically change the label to the current time when the time changes.
推荐答案
Swift 3解决方案
Swift 3 Solution
class ViewController {
@IBOutlet weak var timeLabel: UILabel!
var timer: NSTimer?
let formatter: DateFormatter = {
let tmpFormatter = DateFormatter()
tmpFormatter.dateFormat = "hh:mm a"
return tmpFormatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.getTimeOfDate), userInfo: nil, repeats: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer?.invalidate()
}
func getTimeOfDate() {
var curDate = Date()
timeLabel.text = formatter.string(from: curDate)
}
这篇关于Swift - 显示时间的更新/刷新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!