【问题标题】:Time Label Not Updating时间标签未更新
【发布时间】:2019-01-04 01:36:06
【问题描述】:

我创建了一个标签,在加载应用程序时显示 UTC 时间。 虽然,它不会不断更新,只是保持相同的值。它只会在您重新加载并再次打开应用时更新。

    //UTC Time Formatter
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.dateFormat = "HH:mm"

        //UTC Time
    let utcFrame = CGRect(x: 0, y: 0, width: 20, height: 30)
    let utcLbl = UILabel(frame: utcFrame)
    utcLbl.text = "\(dateFormatter.string(from: Date())) UTC"
    let item = UIBarButtonItem(customView: utcLbl)
    self.navigationItem.setLeftBarButtonItems([item], animated: true)

这是我在 viewDidLoad() 中的代码

【问题讨论】:

  • 您是否尝试过引入一个更新标签的计时器?
  • 我已经尝试过了,但是我会在更新标签的功能中添加什么??? @托比亚斯
  • 您将标签连接到代码中的 IBOutlet,您从 Timer 执行的函数中引用该代码,就像 M.Hem 建议的那样。

标签: swift date time


【解决方案1】:

您需要创建一个计时器来调用函数来更新您的标签

timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(runSomeFunc), userInfo: nil, repeats: true)

然后在函数中更新你的标签

func runSomeFunc(){
    //update labels
}

【讨论】:

  • 我知道该怎么做。我最终在func内部做的是: let formatter = DateFormatter() formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "HH:mm" utcLbl.text = formatter.string(from: Date( )) + "UTC"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2021-12-15
  • 2021-06-25
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多