2017-08-15 109 views
0

我想製作一個由一個按鈕啓動計時器的計時器。當定時器運行時,我需要相同的按鈕來暫停定時器。定時器不會以開始/暫停切換按鈕開始

我處理主要在按鈕標籤的IBAction爲這種行爲:

@IBAction func btn_start(_ sender: Any) {   
    if timerIsRunning == false {   
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)    
     timerIsRunning = true      
    } 

    if timerIsRunning == true {    
     timer.invalidate()    
     timerIsRunning = false    
    }   
} 

我認識到,我可以觸發啓動按鈕幾次,也被觸發時,計時器severalt次,使計時器超速最後。 爲了防止這種行爲,我公司推出了timerIsRunning:BOOL與意外的結果,計時器不啓動了: -/

這是由定時器觸發了我的定時器功能:

func runTimer() {   
    if timeInSeconds >= 0 {   
     timeInSeconds = timeInSeconds - 1    
     updateTimerLabel()    
    }   
} 

燦有誰解釋這一點?並伸出援助之手?

+0

'timerIsRunning = TRUE;如果timerIsRunning == true'呃。 – matt

+0

@matt你是什麼意思?你可以解釋嗎? – boehmatron

+0

他意味着我在我的回答中基本寫過的內容,將變量設置爲「true」,並在下一個語句中檢查其值與真實值。 – luk2302

回答

3

在啓動計時器後應使用return,或使用else。否則,你永遠invalidate新創建的瞬間計時器在你的方法第二if塊:

@IBAction func btn_start(_ sender: Any) {   
    if !timerIsRunning {   
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)    
     timerIsRunning = true      
    } else {    
     timer.invalidate()    
     timerIsRunning = false    
    }   
}