[英]Using timers in swift
我是一個完整的初學者,並且開始學習 Swift 編程語言。 我正在關注 Udemy 的教程,但在設置計時器時遇到了一些問題。
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
var timer1 = Timer()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
label.text = String(counter)
}
@IBAction func start(_ sender: Any) {
timer1 = Timer(timeInterval: 1, target: self, selector: #selector(tim), userInfo: nil, repeats: true)
}
@IBAction func pause(_ sender: Any) {
timer1.invalidate()
}
@IBAction func restart(_ sender: Any) {
timer1.invalidate()
counter = 0
label.text = String(counter)
}
@objc func tim() {
counter += 1
label.text = String(counter)
}
}
這是我的代碼,但計時器不工作。 請告訴我我哪里出錯了。
您需要將計時器添加到RunLoop
RunLoop.current.add(timer1, forMode: .commonModes)
或使用scheduledTimer
timer1 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(tim), userInfo: nil, repeats: true)
同樣在您restart
function 時,您需要再次執行此操作,因為現在您只是使其無效而不是重新啟動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.