我只想实现一个简单的时钟,这是我的 Storyboard:
代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timeLabel: UILabel!
let dateFormatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
dateFormatter.dateFormat = "hh:mm:ss"
_ = Timer.init(timeInterval: 0.1, target: self, selector: #selector(updateClock), userInfo: nil, repeats: true)
}
func updateClock() {
self.timeLabel.text = dateFormatter.string(from: Date())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
标签一直显示00:00:00
。有人可以给我一些建议吗?
最佳答案
您必须创建一个Timer
(您已经完成了)并安排它。这会将其添加到运行循环中,以便它实际上会触发。
最简单的方法是使用 Timer.scheduledTimer(timeInterval:target:selector:userInfo:repeats:)
,它创建并调度 Timer
:
_ = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateClock),
userInfo: nil, repeats: true)
请注意,您可能还应该存储对 Timer
的弱引用。 ,因此当您希望它停止触发时可以使其无效。
关于ios - Swift:为什么即使我使用计时器更改其文本属性,我的标签也不会更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43906423/