进入视图时,我调用一个函数来加载计时器,就像这样...
var count = 10
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}
和update
函数以..
@objc func update() {
while (count != 0) {
count -= 1
countdownLabel.text = "\(count)"
}
timer.invalidate()
}
但是发生的是,当我进入该视图时,立即显示数字0,而不是理想地显示序列9,8,7,6,5,4,3,2,1,0 < / p>
我在做什么错..?
答案 0 :(得分:-1)
迅速4:
var totalTime = 10
var countdownTimer: Timer!
@IBOutlet weak var timeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
}
此方法调用将初始化计时器。它指定了timeInterval(一个方法将被调用的频率)和选择器(该方法将被调用)。
间隔以秒为单位测量,因此要使其像标准时钟一样工作,我们应将此参数设置为1。
func startTimer() {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
// Stops the timer from ever firing again and requests its removal from its run loop.
func endTimer() {
countdownTimer.invalidate()
}
//updateTimer is the name of the method that will be called at each second. This method will update the label
@objc func updateTime() {
timeLabel.text = "\(totalTime)"
if totalTime != 0 {
totalTime -= 1
} else {
endTimer()
}
}