如何在Swift中计时器计数

4

我是一名Swift新手,尝试制作一个计时器。它应该正常计算秒数并在调试器中打印输出。

我尝试了以下代码:

var timer = Timer() 

@IBAction func killTimer(_ sender: AnyObject) {
    timer.invalidate()         
}

@objc func processTimer() {
    print("This is a second")
}

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processTimer), userInfo: nil, repeats: true)
}

我不知道计时器如何计算秒数。使用这段代码,我得到了一个失败的消息:

@objc func processTimer() {
    print("This is second \(Timer + 1)")
}

感谢您的帮助。 A

你能添加你收到的错误吗? - Cristik
3个回答

11

您需要一个计数器变量,在定时器触发时将其递增。

将变量 Timer 声明为可选项,以可靠地使定时器失效(仅一次)。

var timer : Timer?
var counter = 0 

@IBAction func killTimer(_ sender: AnyObject) {
   timer?.invalidate()
   timer = nil
}

@objc func prozessTimer() {
    counter += 1
    print("This is a second ", counter)

}

override func viewDidLoad() {
    super.viewDidLoad()  
    timer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(prozessTimer), userInfo: nil, repeats: true)

}

1
我认为你应该在“这是第二个”之后加上\(counter)。 - surToTheW
1
print("This is a second ", counter) does the same as print("This is a second \(counter)") - vadian

0
如果你想打印经过的时间,可以使用以下代码(如果这是你想要的):
print("time passed: \(Date().timeIntervalSince1970 - timer.fireDate.timeIntervalSince1970)")

0

你需要启动计时器,因为你在代码中只是初始化了它,所以在viewDidLoad中添加以下代码:

timer.fire()

我不确定你想要打印什么,但如果是时间戳,你可以在你的类中添加一个属性。

let formatter = DateFormatter()

并将其配置为以秒和毫秒显示时间

formatter.dateFormat = "ss.SSS" //in viewDidLoad

并在您的打印语句中使用它

print("This is a second \(formatter.string(from(Date())")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接