我有一個計時器,點擊后,button我希望計時器開始,而當timer得到0我想要停止計時器。我知道我可以用invalidate()函式來做到這一點,但我無法訪問計時器這里的代碼
var timer = 5 {
didSet {
label.text = String(timer)
}
}
@IBAction func onClickAnimate(_ sender: Any) {
let timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
if timer > 0 {
timer -= 1
}
if timer == 0 {
timer = 5
timerCount.invalidate() // error is here
}
}
如果我決定timerCount全域創建,則會出現錯誤unrecognized selector sent to instance 0x600003b466a0"
任何解決方案都將被應用
uj5u.com熱心網友回復:
解決方案1:創建一個變數
var timerCount:Timer!
@IBAction func onClickAnimate(_ sender: Any) {
timerCount = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter(){
if timer > 0 {
timer -= 1
}
if timer == 0 {
timer = 5
timerCount.invalidate()
}
}
解決方案2:使用塊
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timerCount in
if self.timer > 0 {
self.timer -= 1
}
else
if self.timer == 0 {
self.timer = 5
timerCount.invalidate()
}
}
uj5u.com熱心網友回復:
您應該timerCount在函式之外但在類內,以便您可以訪問它:
class ViewController: UIViewController {
let timerCount: Timer = Timer()
}
然后,洗掉let關鍵字。
您現在可以訪問您的timerCount.
uj5u.com熱心網友回復:
制作Global variable in Class這樣的:
var timerCount = Timer()
Boom!!!... 現在您可以訪問它了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364964.html
上一篇:從字串字典中參考字串檔案
