首页 > 解决方案 > 在 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
    }

我希望我的应用能够实时更新时间标签。提前致谢。这可能是一个非常简单的修复。

标签: iosswiftxcodetime

解决方案


根据您的要求使用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())
    }
}

推荐阅读