[英]Reset countdown timer value to the default value saved in the Array
我正在从数组中的默认 Int 值创建倒数计时器,但我无法弄清楚如何将计时器重置为数组中的原始值。 这意味着当用户按下“停止酿造”时,倒数计时器将从例如 5 分钟重新开始。 有人可以帮我找出我做错了什么或遗漏了什么吗? 我正在迈出 iOS 开发的第一步。
提前致谢!
我的代码:
@objc func runTimer() {
cafe.time -= 1
labelCowntdownTimer.text = "\(cafe.time)"
// MM:SS:_
let flooredCounter = cafe.time
let minute = (flooredCounter % 3600) / 60
var minuteString = "\(minute)"
if minute < 10 {
minuteString = "0\(minute)"
}
let second = (flooredCounter % 3600) % 60
var secondString = "\(second)"
if second < 10 {
secondString = "0\(second)"
}
labelCowntdownTimer.text = "\(minuteString):\(secondString)"
}
//Mark: - resetTimer
@objc func resetTimer() {
timer.invalidate()
//cafe.time
runTimer()
}
//Mark: - ButtonPressed - Start Timer
@IBAction func startButtonPressed(_ sender: Any) {
if !isTimerRunning {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
isTimerRunning = true
startButton.setTitle("Stop Brewing", for: .normal)
} else {
resetTimer()
isTimerRunning = false
startButton.setTitle("Start Brewing", for: .normal)
}
}
在您的viewDidload()
或每当您获得存储在数组中的值时,将该值存储在一个变量中。
var initialValueOfTime = 0 // the initial value is stored here. which is 300
override func viewDidLoad() {
super.viewDidLoad()
initialValueOfTime = cafe.time
}
@objc func runTimer() {
if isTimerRunning {
cafe.time -= 1
} else {
cafe.time = initialValueOfTime
}
labelCowntdownTimer.text = "\(cafe.time)"
// MM:SS:_
let flooredCounter = cafe.time
let minute = (flooredCounter % 3600) / 60
var minuteString = "\(minute)"
if minute < 10 {
minuteString = "0\(minute)"
}
let second = (flooredCounter % 3600) % 60
var secondString = "\(second)"
if second < 10 {
secondString = "0\(second)"
}
labelCowntdownTimer.text = "\(minuteString):\(secondString)"
}
//Mark: - resetTimer
@objc func resetTimer() {
timer.invalidate()
runTimer()
}
//Mark: - ButtonPressed - Start Timer
@IBAction func startButtonPressed(_ sender: Any) {
if !isTimerRunning {
isTimerRunning = true
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
startButton.setTitle("Stop Brewing", for: .normal)
} else {
isTimerRunning = false
resetTimer()
startButton.setTitle("Star Brewing", for: .normal)
}
}
试试下面的代码
@objc func resetTimer() {
timer.invalidate()
timer = nil //You should also need to nil to a timer to stop it.
//runTimer() - also comment this line as its not needed to call this function after stop timer.
//Reinitialize all your required variable here to calculate the time
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.