[英]stoping timer on viewcontroller dismiss swift
我在視圖控制器中有一個計時器,用於檢查功能。 但是,如果我關閉設置了計時器的Viewcontroller,它仍然繼續,或者如果時間到零,我想自動關閉Viewcontroller。 在我現在的情況下,如果我在視圖控制器未達到零的情況下手動關閉視圖控制器,則時間仍將持續到計數器達到ero為止。
我該如何設置代碼,以便如果我自己解雇Viewcontroller,時間將停止並且不會達到零,從而使我在時間為零時所處的條件無法運行。
下面是我的代碼
override func viewDidLoad() {
super.viewDidLoad()
var _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerLabel.text = "\(counter)"
}
@objc func updateCounter() {
//you code, this is an example
if counter >= 0 {
timerLabel.text = "\(counter)"
counter -= 1
}
if counter == 0 {
Print.HOMEPRINT("COUNTER GOT TO ZERO")
dismiss(animated: true, completion: nil)
}
}
為計時器聲明一個公共變量,然后在要停止時使其無效。
var timer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerLabel.text = "\(counter)"
}
@objc func updateCounter() {
//you code, this is an example
if counter >= 0 {
timerLabel.text = "\(counter)"
counter -= 1
}
if counter == 0 {
timer?.invalidate()
Print.HOMEPRINT("COUNTER GOT TO ZERO")
dismiss(animated: true, completion: nil)
}
}
為Timer創建一個全局變量
var myTimer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
timerLabel.text = "\(counter)"
}
@objc func updateCounter() {
//you code, this is an example
if counter >= 0 {
timerLabel.text = "\(counter)"
counter -= 1
}
if counter == 0 {
if (myTimer != nil)
{
myTimer?.invalidate()
myTimer = nil
}
Print.HOMEPRINT("COUNTER GOT TO ZERO")
dismiss(animated: true, completion: nil)
}
}
// MARK:手動關閉控制器
@objc func dismissButtonTapped()
{
if (myTimer != nil)
{
myTimer?.invalidate()
myTimer = nil
}
dismiss(animated: true, completion: nil)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.