就我而言,我的應用程式有三個視圖控制器(有 loginview、homeview、menuview)
在 homeview 中,我設定了一個計時器,每 10 秒從服務器重新加載資料。代碼如下圖:
Timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(loadData), userInfo: nil, repeats: true)
let storyBoard: UIStoryboard = UIStoryboard(name: "mapFirstPage", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "menuSetupVC") as! menuSetupViewController
newViewController.modalPresentationStyle = .fullScreen
self.navigationController?.pushViewController(newViewController, animated: true)
當我去menuview時,有一個注銷btn,它可以帶我到loginview。但是計時器仍在后臺運行......
當我在選單視圖中時如何停止它。
uj5u.com熱心網友回復:
您可以將通知觀察者添加到您的視圖控制器并在您點擊注銷操作時通知。
uj5u.com熱心網友回復:
let storyBoard: UIStoryboard = UIStoryboard(name: "mapFirstPage", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "menuSetupVC") as! menuSetupViewController
Timer!.invalidate()// will stop the timer
newViewController.modalPresentationStyle = .fullScreen
self.navigationController?.pushViewController(newViewController, animated: true)
uj5u.com熱心網友回復:
如果你只有這三個視圖控制器,你可以像單例一樣設定 Timer,這樣你就可以在代碼的任何部分訪問它們,也可以根據需要啟用和禁用。
所以你可以使用函式 .invalidate() 來阻止它
func startTimer() {
stopTimer()
guard self.timer == nil else { return }
self.timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(loadData), userInfo: nil, repeats: true)
}
func stopTimer() {
guard timer != nil else { return }
timer?.invalidate()
timer = nil
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/344913.html
上一篇:Unity獲取鍵盤以及場景切換
