我正在尝试为我的应用设置倒数计时器。我的代码有效,因此每次拖动图像 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)
}
}
最佳答案
刚发现我的问题。我根本没有重置计时器。首先,我试图在“ Action ”函数中重置它,但我只需要将它移到底部 if 语句即可解决我所有的问题。此代码适用于在发生特定操作时尝试重置计时器的任何人。
class SecondViewController: UIViewController
{
var addOne = 0
func startTimer() {
timeClock -= 1
time.text = "Time: " + String(timeClock)
if timeClock <= 0 {
timer.invalidate()
//show game over
}
}
func resetTimer() {
timer.invalidate()
timeClock = 3
}
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)"
resetTimer()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(SecondViewController.startTimer), userInfo: nil, repeats: true)
smallDot.center = spawnRandomPosition()
}
}
关于ios - 计时器进入底片/不重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45260446/