2015-11-23 48 views
0

我需要按順序啓動計時器(一個接一個地)。當然,我需要更新帶定時器結果的Label。例如,我有兩個階段(50秒和10秒),我需要進行一系列階段:50-10-50-10-50-10。 我該怎麼辦?如何在Swift 2.0中啓動一系列計時器?

import UIKit 

class StartTimerViewController: UIViewController { 

let firstPeriodTime = 50 
let secondPeriodTime = 10 
var currentPeriodTime: Int! 

let repetitionTime = 3 

var timer: NSTimer! 
var timeCount = 0 

@IBOutlet weak var timerLabel: UILabel! 


// MARK: - IBAction method implementation 

@IBAction func start(sender: AnyObject) { 

    // I know it's wrong... This is my question!!!!! 

    var i = 1 

    while i <= repetitionTime { 

     currentPeriodTime = firstPeriodTime 
     startTimer() 

     currentPeriodTime = secondPeriodTime 
     startTimer() 

     i = i + 1 
    } 
} 


// MARK: - Timer method implementation 

func startTimer() { 
    timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: "updateCounter", userInfo: nil, repeats: true) 
    print("timer start") 
} 

func updateCounter() { 

    if timeCount < currentPeriodTime { 
     timeCount++ 
     let currentTime = Double(currentPeriodTime - timeCount) 
     timerLabel.text = timeString(currentTime) 
    } 
    else { 
     timer.invalidate() 
     timeCount = 0 
    } 
} 


func timeString(time:NSTimeInterval) -> String { 
    let minutes = Int(time)/60 
    let seconds = time - Double(minutes) * 60 
    return String(format:"%02i:%02i",minutes,Int(seconds)) 
} 


override func viewDidLoad() { 
    super.viewDidLoad() 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
} 
+0

代碼你的意思是1後50秒計時器u需要啓動另一個10秒計時器? – vinbhai4u

+0

是的,你是對的 –

回答

1

請使用以下

@IBOutlet weak var _lblTimer: UILabel! 
    var timer = NSTimer() 
    var intValue = 0 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update50:", userInfo: nil, repeats: true) 
    } 

    func update50(timer : NSTimer){ 
     intValue += 1 
     _lblTimer.text = intValue.description 
     if(intValue == 50){ 
      intValue = 0 
      timer.invalidate() 
      self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update10:", userInfo: nil, repeats: true) 
     } 
    } 

    func update10(timer : NSTimer){ 
     intValue += 1 
     _lblTimer.text = intValue.description 
     if(intValue == 10){ 
      intValue = 0 
      timer.invalidate() 
      self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update50:", userInfo: nil, repeats: true) 
     } 
    } 
+0

謝謝你的時間! 我需要一些方法來停止這個循環。我會試試看... –

+0

@vivatum你可以放置一些按鈕來停止並使用timer.invalidate()來停止定時器 – vinbhai4u

+0

它的工作原理。非常感謝! –