如何在Swift 2.0中启动一系列计时器?

时间:2015-11-23 10:09:18

标签: ios swift timer nstimer

我需要按顺序启动计时器几次(一个接一个)。当然我需要使用计时器结果更新Label。 例如,我有两个时段(50秒和10秒),我需要制作一系列时段:50-10-50-10-50-10。 我该怎么办?

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.
}
}

1 个答案:

答案 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)
        }
    }