this is i seting a timer function, the code like this:
@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
}
but, when i click the stop func, this function not work. mean is the timer not stop. timer stil working…… why? thank you for your time!!
I think you didn't set timer
value
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector:#selector(ViewController.action),
userInfo: nil,
repeats: true)
Ensure that you are invalidating correct instance of Timer. Like in start function
, you didn't assign timer instance to any object, but in stop function
,you are using timer
vaiable to stop that timer. Which means you try to invalidate a variable, which never instantiated.
Still try below function to stop timer, after assigning timer variable .
@IBAction func stop(_ sender: UIButton) {
start = false
timer.invalidate()
timer = nil
time = 0
}
Hope this work
First you have to declare it as fileprivate as below:
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()
}
you are confusing between variable stop and func stop.
also you dont need 2 parameter to manage stop/start status
-- for your question, you should retain the timer variable to able to use it in other func declare a global timer
var timer: Timer!
then
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.action), userInfo: nil, repeats: true)
now you can invalidate it anywhere
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.