Ios swift3和xFF0C;我的计时器可以';不要停下来。为什么?
这是我设置的一个定时器功能,代码如下:Ios swift3和xFF0C;我的计时器可以';不要停下来。为什么?,ios,swift,Ios,Swift,这是我设置的一个定时器功能,代码如下: @IBAction func start(_ sender: UIButton) { Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.action), userInfo: ni
@IBAction func start(_ sender: UIButton) {
Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
}
@objc func action() {
hoursMinutesSeconds()
if stop == true{
start = false
timer.invalidate()
timer.invalidate()
time = 0
}
}
@IBAction func stop(_ sender: UIButton){
start = false
timer.invalidate()
timer.invalidate()
time = 0
}
但是,当我单击“停止”函数时,该函数不起作用。意思是计时器没有停止。计时器还在工作……为什么?谢谢你抽出时间 我认为您没有设置
计时器值
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
我认为您没有设置计时器值
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
确保正在使计时器的正确实例无效。
与在启动函数
中一样,您没有将计时器实例分配给任何对象,但在停止函数
中,您正在使用计时器
来停止该计时器。
这意味着您试图使从未实例化的变量无效
在分配计时器变量后,仍然尝试下面的函数停止计时器
@IBAction func stop(_ sender: UIButton) {
start = false
timer.invalidate()
timer = nil
time = 0
}
希望这项工作确保您正在使计时器的正确实例无效。
与在启动函数
中一样,您没有将计时器实例分配给任何对象,但在停止函数
中,您正在使用计时器
来停止该计时器。
这意味着您试图使从未实例化的变量无效
在分配计时器变量后,仍然尝试下面的函数停止计时器
@IBAction func stop(_ sender: UIButton) {
start = false
timer.invalidate()
timer = nil
time = 0
}
希望这项工作首先,您必须将其声明为fileprivate,如下所示:
fileprivate var timer = Timer()
@IBAction func start(_ sender: UIButton) {
self.timer = Timer.scheduledTimer(timeInterval: 4,
target: self,
selector: #selector(self.updateTimerForLocation),
userInfo: nil,
repeats: true)
}
@IBAction func stop(_ sender: UIButton) {
timer.invalidate()
}
首先,您必须将其声明为fileprivate,如下所示:
fileprivate var timer = Timer()
@IBAction func start(_ sender: UIButton) {
self.timer = Timer.scheduledTimer(timeInterval: 4,
target: self,
selector: #selector(self.updateTimerForLocation),
userInfo: nil,
repeats: true)
}
@IBAction func stop(_ sender: UIButton) {
timer.invalidate()
}
您混淆了变量stop和func stop
此外,您不需要2个参数来管理停止/启动状态
--
对于你的问题,
您应该保留计时器变量,以便能够在其他函数中使用它
声明一个全局计时器
var定时器:定时器代码>
然后
timer=timer.scheduledTimer(时间间隔:1,
目标:自我,
选择器:#选择器(ViewController.action),
userInfo:nil,
重复:true)
现在,您可以在任何地方使其无效您混淆了变量停止和函数停止
此外,您不需要2个参数来管理停止/启动状态
--
对于你的问题,
您应该保留计时器变量,以便能够在其他函数中使用它
声明一个全局计时器
var定时器:定时器代码>
然后
timer=timer.scheduledTimer(时间间隔:1,
目标:自我,
选择器:#选择器(ViewController.action),
userInfo:nil,
重复:true)
现在,您可以在任何地方使其无效是否设置了断点?代码处理是否正确?是否设置了断点?你的代码被正确处理了吗?上帝,你是对的!现在,这个代码开始工作了!!非常感谢你。两天来我一直在问这个问题。上帝,你说得对!现在,这个代码开始工作了!!非常感谢你。两天来我一直在做这个问题。