需要帮助更新我的应用程序上的时间,这是静态的
我正在为学校编码一个应用程序,并提供一个欢迎页面,上面有“您好,目前是xx; xx。仅更新一次。
func getCurrentTime() -> String {
let formatter = DateFormatter()
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())
return dateString
}
I am coding a app for school, and have a welcome page with the "hello it is currently xx;xx. I have the time updating, but I cant figure a way out to make it constantly refresh, as I test the build, it only updates once. here is my code
func getCurrentTime() -> String {
let formatter = DateFormatter()
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())
return dateString
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如上所述,您在某个时间点抓住日期。您需要一种机制来重复获得日期并在更改UI时更新。最简单的方法是使用计时器。
为了最大程度地减少加载,您只能在时间更改时更新UI。下面的摘要每分钟更新,但是您可以使用几秒钟的方法采用相同的方法。
As mentioned above, you are grabbing the date at a point in time. You need a mechanism to repeatedly obtain the date and update the UI when it changes. The simplest way to do this is with a timer.
To minimise load you should only update the UI when the time changes. The snippet below updates every minute, but you can take the same approach with seconds.
目前,您要做的只是一次抓住时间,因此解决方案是不断运行您的功能。为此,我们可以在循环时使用无限的方法,通常您会有一个可能破坏循环的条件,但是在时间的情况下,我们只能有一个永远不会评估错误的条件,所以真实。
这将允许返回的值始终正确,但是我假设某些其他函数正在调用getCurrenttime(),而不是getCurrenttime设置显示的值,因此您必须在while循环中设置该值,就像这样。
Currently what you're doing is only grabbing the time once, so the solution is to constantly run your function. To do this we can use an infinite while loop, generally you'd have a condition that might break the loop but in the case of time we can just have a condition that will never evaluate to false, so true.
This will allow the returned value to always be correct however I'm assuming that some other function is calling getCurrentTime() rather than getCurrentTime setting the value that's displayed thus you would have to set that value inside the while loop, kind of like this.
我没有关于Swift的语法。但是该算法与任何语言都是相似的。在JavaScript中,您可以使用setInterval函数。
我已经搜索了SetInterval的一些快速替代方案,并找到了这一点。
I don't have any syntax about the Swift. But the algorithm is similar any language. In Javascript you can use setInterval function.
I have search a little Swift alternatives of setInterval and found this.