ios - 在 Swift 4 中显示实时时间标签?
问题描述
我的时间标签显示时间,当我打开我的应用程序但它不会实时更新它。我看了其他答案,但它们没有意义。
// 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 - 在 Mac 上运行的 ios 应用程序上,getPlatformName() 会返回什么?
- amazon-web-services - 在实例中更新 Hosts 文件,以便它们可以通过 DN 进行通信
- asp.net-core - 如何在 Blazor 中将非对象的数据类型作为模型传递给表单?
- ms-word - MS Word 邮件合并:记录中出现字段计算错误#
- sql - Split_part 未在 redshift sql 查询中提供完整数据
- python - python:将两列合并为一并复制相应的单元格
- javascript - 如何从属性中的内联javascript调用元素本身?特别删除属性
- google-apps-script - Big Query API via Apps script - 我在一个很大的表上遇到错误,但在一个较小的表上工作。通过应用程序脚本有大小限制吗?
- mongodb - 我可以在聚合管道中生成唯一的字符串 _id
- arrays - 为什么数组溢出在这里返回 0?