2015-12-26 67 views
0

我正在嘗試做一個倒數計時器,從60秒倒計時,然後停止時,它變爲0.但定時器保持進入負秒。任何建議表示讚賞。代碼:IOS快速倒數計時器不會停止

@IBOutlet var timeCounter: UILabel! 
var second = 60 

var timer = NSTimer() 

var timerRunning = true 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view. 


    setTimer() 
    timerCounting() 
} 

func setTimer(){ 
    second -= 1 
    timeCounter.text = "\(second)" 


} 

func timerCounting(){ 
    if(timerRunning == true){ 

     timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setTimer"), userInfo: nil, repeats: true) 
     timerRunning = true 
     if second == 0 { 
      timerRunning = false 
      timer.invalidate() 


     } 


    } 


} 

回答

6

你必須失效移入setTimer功能,因爲在當前位置將永遠不會被觸發,因爲timerCounting只調用一次 - 在開始的時候。在操場

func setTimer(){ 
    second -= 1 
    timeCounter.text = "\(second)" 
    if second == 0 { 
     timerRunning = false 
     timer.invalidate() 
    } 
} 
+0

真棒謝謝你這個工作,等待4個分鐘接受答案 – Ace

0

玩這個

import XCPlayground 
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 
import Foundation 


@objc class C:NSObject { 
    var timer: NSTimer? 
    var second = 5 
    func setTimer(){ 
     if c.second < 0 { 
      print("the timer fires the last time here ...") 
      timer?.invalidate() 
     } else { 
      print(second) 
      second -= 1 
     } 
    } 
} 

let c = C() 

func timerCounting(){ 
     c.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: c, selector: Selector("setTimer"), userInfo: nil, repeats: true) 
} 

timerCounting()