Time is variable in Swift
Overview. I am trying to create a quiz where someone has to answer questions within a certain amount of time. They have 10 seconds to resolve each issue, or it will move to the next controller. The problem is that whenever I hit the next question before it gets to full time, it keeps counting down to 10. What should happen is it should stop timing for that question.
So far, I have implemented the following code to try and make this work. var time = 0
and first created a global variable called time. Then I created the timer code like this:var count = 10
@IBOutlet var countDownLabel: UILabel!
Then I create a label that will mark every second until it reaches 0. The code looks like this:
if(count > 0) {
countDownLabel.text = String(count)
count -= 1
time += 1
}
print (time)
if (count <= 0 ) {
count = 10
self.performSegue(withIdentifier:"NextQuestion1", sender: nil)
}
Summary: The countdown time for each time should increase. Then the time will be displayed at the end. I will be happy to provide help in solving this problem.
source to share
When you press the next button, you need to invalidate the timer so that it won't count.
Say you created your timer this way.
let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(YourSegueFunction), userInfo: nil, repeats: false)
Then when you click on the next button use the following line of code to stop the timer
timer.invalidate()
Here is a demo
source to share