2016-01-12 126 views
0

我是Swift的新手 - 嘗試爲iPhone/iPad構建應用程序。希望您能夠幫助我。swift:停止倒數計時器爲零

我想包括一個從04:00分鐘到00:00倒計時的計時器。然後它應該停止在零並觸發音效(我還沒有嘗試過)。當您按下開始按鈕時,倒數開始(在我的代碼中,startTimer和stopTimer指向同一個按鈕;但是,按鈕僅在開始時被按下一次)。

計時器啓動並倒計時就好了。它按計劃將秒轉換成分鐘。但是,我的主要問題是我無法讓倒計時停止在零。它繼續超越00:0-1等。我該如何解決這個問題?

import Foundation 
import UIKit 
import AVFoundation 


class Finale : UIViewController { 



    @IBOutlet weak var timerLabel: UILabel! 


    var timer = NSTimer() 
    var count = 240 
    var timerRunning = false 




    override func viewDidLoad() { 
     super.viewDidLoad() 

    } 



    func updateTime() { 
     count-- 


     let seconds = count % 60 
     let minutes = (count/60) % 60 
     let hours = count/3600 
     let strHours = hours > 9 ? String(hours) : "0" + String(hours) 
     let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes) 
     let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds) 
     if hours > 0 { 
      timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)" 
     } 

     else { 
      timerLabel.text = "\(strMinutes):\(strSeconds)" 
     } 

    } 



    @IBAction func startTimer(sender: AnyObject) { 

     var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true) 

    } 

func stopTimer() { 

    if count == 0 { 
     timer.invalidate() 
     timerRunning = false 
      } 
    } 



    @IBAction func stopTimer(sender: AnyObject) { 
     timerRunning = false 
    if count == 0 { 
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("stopTimer"), userInfo: nil, repeats: true) 
     timerRunning = true 
     }} 

} 
+0

http://stackoverflow.com/a/29583418/2303865 –

回答

1

記住,你的定時器不倒數至零 - 您實現您的代碼。計時器每秒都會觸發。

在你的錄入功能,你需要無效計時器,並調用你的聲音功能,當計時器運行過程

+0

謝謝,羅素。我如何使其無效?我現在嘗試添加如果計數== 0 { timer.invalidate() timerRunning = false } updateTime函數,但它不停止。 – mojomo

+0

這應該這樣做 - 但你有兩個版本的計時器!您有一個用類範圍定義的變量,但您使用的變量僅在啓動函數中定義。在初始化計時器之前,您需要刪除'var',以便僅使用一個變量 – Russell

2
func updateTime() { 
     count-- 


     let seconds = count % 60 
     let minutes = (count/60) % 60 
     let hours = count/3600 
     let strHours = hours > 9 ? String(hours) : "0" + String(hours) 
     let strMinutes = minutes > 9 ? String(minutes) : "0" + String(minutes) 
     let strSeconds = seconds > 9 ? String(seconds) : "0" + String(seconds) 
     if hours > 0 { 
      timerLabel.text = "\(strHours):\(strMinutes):\(strSeconds)" 
     } 

     else { 
      timerLabel.text = "\(strMinutes):\(strSeconds)" 
     } 
    stopTimer() 
} 
0

耶!它的工作!我用了兩個答案的組合。我在我的updateTimer函數中添加了stopTimer(),我從計時器中刪除了「var」,並刪除了我的代碼的最後一段/ IBAction。十分感謝大家!現在我會嘗試添加聲音。 :)

+0

酷 - 記得標記幫助您的答案:-) – Russell