为什么我无法使计时器无效?我不断收到错误消息:
类型的定义'定时器'没有会员'无效'
有人可以指出我正确的方向吗?以下是我的代码。
var totalTimeInSec = Double()
var timer = Timer()
var timeInSec = 00.0
{
didSet {
if timeInSec <= 0 {
timer.invalidate() // This is where the error occurs.
startBtn.setTitle("Start", for: .normal)
}
}
}
func initialSettings() {
timerSetting.addTarget(self, action: #selector(self.settingTimer(sender:)), for: UIControlEvents.valueChanged)
//timerSetting.addTarget(self, action: #selector(CollectionViewController.collectionView(_:cellForItemAt:)), for: UIControlEvents.valueChanged)
}
func settingTimer(sender: UIDatePicker) {
let timeFormat = DateComponentsFormatter()
timeFormat.allowedUnits = [NSCalendar.Unit.second, NSCalendar.Unit.minute, NSCalendar.Unit.hour]
timeFormat.unitsStyle = DateComponentsFormatter.UnitsStyle.abbreviated
timerLabel?.text = timeFormat.string(from: sender.countDownDuration)
timeInSec = timerSetting.countDownDuration
timeInSec = totalTimeInSec
}
@IBAction func timerStart(_ sender: UIButton) {
if sender.titleLabel?.text == "Start" {
resetCounter()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.changeLabelText), userInfo: nil, repeats: true)
startBtn.setTitle("Stop", for: .normal)
} else {
timer.invalidate()
startBtn.setTitle("Start", for: .normal)
showTimer.animate(fromAngle: showTimer.angle, toAngle: 0, duration: 0.5, completion: nil)
}
}
之前我曾使用timer.invalidate()
没有问题,但似乎无法弄清楚为什么会发生这种情况。