ios - Swift:为什么即使我使用计时器更改其文本属性,我的标签也不会更新?

标签 ios swift

我只想实现一个简单的时钟,这是我的 Storyboard:

enter image description here

代码:

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/

相关文章:

ios - 无法使用 XCode 9.3 将 Xamarin.iOS 应用程序部署到设备

ios - UIActivityIndi​​catorView在正确的时间显示

json - JSON混合模式数据怎么写?

ios - CALayers : A) Can I draw directly on them and B) How to make a width adjustment on a superlayer affect a sublayer

swift - 如何在延迟滚动时更改 UIView 大小

objective-c - 如何从 Storyboard 对 Nib 进行转场

iphone - 高效地访问数组内的数组

ios - 如何在 iOS 7 中超过 180 秒的后台运行 NSTimer?

swift - 解码具有通用数组属性的结构

ios - 自定义 UITableViewCell 重叠对象