我的时间标签显示时间,当我打开我的应用程序时,它不会实时更新。我查看了其他答案,但它们没有意义。
// CURRENT TIME
@IBOutlet weak var currentTimeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
getCurrentTime()
}
// FORMAT TIME
func getCurrentTime(){
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm"
let str = formatter.string(from: Date())
currentTimeLabel.text = str
}
我希望我的应用实时更新时间标签。提前致谢。这可能是一个非常简单的修复。
最佳答案
根据您的要求使用Timer
,
class ViewController: UIViewController {
@IBOutlet weak var currentTimeLabel: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
getCurrentTime()
}
private func getCurrentTime() {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.currentTime) , userInfo: nil, repeats: true)
}
@objc func currentTime() {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm"
currentTimeLabel.text = formatter.string(from: Date())
}
}
关于ios - 在 Swift 4 中显示实时时间标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53902900/