I am trying to set a countdown timer for my app. My code works so that every time the image whiteDot is dragged and containing smallDot the countdown begins, and smallDot is spawned in a random position on screen. I have a couple questions
1.) I am trying to get the timer to reset to 2 seconds after every time the "if (whiteDot.frame.contains(smallDot.frame) && smallDot.image != nil)" statement is executed.
2.) Everytime the "if" statement is executed once, it counts down normally, but when it is executed again before the countdown hits zero, it starts going into negative numbers and counting faster than 1 second.
import UIKit
var timeClock = 2
class SecondViewController: UIViewController {
func startTimer() {
timeClock -= 1
time.text = "Time: " + String(timeClock)
if whiteDot.frame.contains(smallDot.frame) && timeClock > 0 {
timeClock = 2
}
else if timeClock == 0 || timeClock < 0 {
timer.invalidate()
}
}
var timer = Timer()
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.view)
if (whiteDot.frame.contains(smallDot.frame) && smallDot.image != nil) {
addOne += 1
score.text = "\(addOne)"
smallDot.center = spawnRandomPosition()
timeClock = 2
if timeClock == 0 || timeClock < 0 {
timer.invalidate()
}
else if timeClock > 0 && (whiteDot.frame.contains(smallDot.frame)){
timeClock = 2
}
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(SecondViewController.action), userInfo: nil, repeats: true)
}
}