user
user

Reputation: 83

swift: Show seconds in label.

I have this array of seconds:

var modeLight = [5,30,60,30,60,30]

And I have timer:

@IBOutlet weak var timerLabel: UILabel!
var seconds = 60
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false

@IBAction func startAction(_ sender: UIButton) {
    if isTimerRunning == false {
                    runTimer()
                }
}

func runTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(MasterViewController.updateTimer)), userInfo: nil, repeats: true)
        isTimerRunning = true
    }

    @objc func updateTimer() {
        if seconds < 1 {
            timer.invalidate()
            //Send alert to indicate "time's up!"
        } else {
            seconds -= 1
            timerLabel.text = timeString(time: TimeInterval(seconds))
        }
    }

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

I want to take seconds value from modeLight and show it in timerLabel. After first element (for example 5) will expire I want to show next and etc. How to do it?

Upvotes: 0

Views: 619

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51965

You need to keep track of the array index to use.

Add an index property and initialise it

var modeLight = [5,30,60,30,60,30]
var timerIndex: Int 
var timer: Timer!

Use index in your updateTimer() func

func runTimer() {
    timerIndex = 0
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(MasterViewController.updateTimer)), userInfo: nil, repeats: true)
}

@objc func updateTimer() {
    if seconds < 1 {
        timerIndex += 1
        if timerIndex >= modeLight.count { // to be safe
            endTimer()
            return
        }
        seconds = modeLight[timerIndex]
    } else {
        seconds -= 1
    }

    timerLabel.text = timeString(time: TimeInterval(seconds))
}

private func endTimer() {
    timer.invalidate()
    timerLabel.text = "00:00:00"
}

Upvotes: 1

Related Questions