我正在尝试制作一个倒数计时器。一切正常,但我的计时器不按规定间隔计算(1秒);相反,它会一直向下计数,每次都给我0。没有运气就做了很多搜索。我能找到的所有示例都显示了类似的timeInterval参数。
var timer = Timer()
var remainingTime = 120
@objc func timerCount () {
if remainingTime > 0 {
while remainingTime > 0 {
remainingTime -= 1
timerLabel.text = String(remainingTime)
print(remainingTime)
}
} else {
timer.invalidate()
}
}
@IBAction func pauseButton(_ sender: Any) {
timer.invalidate()
}
@IBAction func playButton(_ sender: Any) {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerCount), userInfo: nil, repeats: true)
}
答案 0 :(得分:1)
您的代码无效的原因是您在 timerCount()方法中放置了不必要的while循环。你不需要这样做。您的计时器将在每个时间间隔后触发此方法。在第一次调用时,while循环使你的remainingTime为0.这就是你每次都立刻得到0的原因。
你只需要删除while循环。
答案 1 :(得分:0)
你能尝试这样吗
var timer = Timer()
var remainingTime = 120
@objc func timerCount () {
let date = NSDate()
let nowdate = UserDefaults.standard.object(forKey: "NowDate") as! Date
let miniute = nowdate.timeIntervalSince(date as Date)
print(Int(miniute))
if (Int(miniute) == 0) {
timer.invalidate()
UserDefaults.standard.removeObject(forKey: "NowDate")
} else {
timerLabel.text = String(Int(miniute))
}
}
@IBAction func pauseButton(_ sender: Any) {
timer.invalidate()
UserDefaults.standard.removeObject(forKey: "NowDate")
}
@IBAction func playButton(_ sender: Any) {
let CurrentDate = NSDate()
let NowDate = CurrentDate.addingTimeInterval(TimeInterval(remainingTime))
UserDefaults.standard.set(NowDate, forKey: "NowDate")
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerCount), userInfo: nil, repeats: true)
}