我有以下几秒钟:
var modeLight = [5,30,60,30,60,30]
我有计时器:
@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)
}
我想从modeLight
中获取秒值并将其显示在timerLabel
中。在第一个元素(例如5
)到期之后,我想显示下一个,等等。
答案 0 :(得分:1)
您需要跟踪要使用的数组索引。
添加索引属性并对其进行初始化
var modeLight = [5,30,60,30,60,30]
var timerIndex: Int
var timer: Timer!
在您的updateTimer()
函数中使用索引
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"
}