【发布时间】:2017-08-05 21:16:42
【问题描述】:
我正在尝试用当前时间更新标签。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
let date = Date()
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
func updateTime(){
label.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .long)
}
}
当我在 updateTime() label.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .long) 使用时,我得到了我想要的结果
当我使用label.text = DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .long)时
计时器不工作。有人可以解释一下吗? ?
据我了解,如果我使用日期而不是 Date(),那么我需要一个计时器/计数器来计数和计算。如果有,有什么建议吗?
非常感谢
P
【问题讨论】:
-
date是一个常数值。所以即使updateTime()每秒被调用一次,它每次都将标签设置为相同的值。 -
@vacawama。非常感谢。以及如何表示显示从日期和每分钟/秒等开始计数的标签?
-
您是否要让标签从
0:00开始,然后每秒计数? -
不,基本上我希望标签从日期开始( let date = Date() )并开始每秒计数。通过解决这个小例子,我可以解决我的大问题:)
-
像在第一个示例中那样使用
Date()调用有什么问题。你说那行得通。有什么让你无法接受的?
标签: ios swift timer dateformatter