我正在尝试为我的应用程序设置倒计时器。我的代码是这样的,每次拖动图像whiteDot并包含smallDot时,倒计时开始,并且smallDot在屏幕上的随机位置生成。我有几个问题:
1.) 我正在尝试在执行"if (whiteDot.frame.contains(smallDot.frame) && smallDot.image != nil)"语句后,将计时器重置为2秒。
2.) 每次执行"if"语句一次时,它会正常倒计时,但当在倒计时结束之前再次执行它时,它会开始进入负数并比1秒更快地倒计时。
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)
}
}