我正在尝试制作一个倒数计时器,它从 60 秒开始倒计时,然后在倒数到 0 时停止。但是计时器一直在倒计时。任何建议表示赞赏。代码:
@IBOutlet var timeCounter: UILabel!
var second = 60
var timer = NSTimer()
var timerRunning = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setTimer()
timerCounting()
}
func setTimer(){
second -= 1
timeCounter.text = "\(second)"
}
func timerCounting(){
if(timerRunning == true){
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setTimer"), userInfo: nil, repeats: true)
timerRunning = true
if second == 0 {
timerRunning = false
timer.invalidate()
}
}
}
最佳答案
您必须将失效移动到 setTimer
函数中,因为在它的当前位置将永远不会被触发,因为 timerCounting
仅在开始时被调用一次。
func setTimer(){
second -= 1
timeCounter.text = "\(second)"
if second == 0 {
timerRunning = false
timer.invalidate()
}
}
关于IOS swift倒数计时器不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34471966/