计时器进入否定/不重置

时间:2017-07-23 00:10:08

标签: ios swift timer counter countdown

我正在尝试为我的应用设置倒数计时器。我的代码工作,以便每次拖动图像whiteDot并包含smallDot倒计时开始,并且smallDot在屏幕上随机产生。我有几个问题

1。)我想在每次" if(whiteDot.frame.contains(smallDot.frame)&& smallDot.image!= nil)之后让计时器重置为2秒#34;声明已经执行。

2。)每次"如果"语句执行一次,它会正常倒计时,但在倒计时到零之前再次执行时,它会开始变为负数并且计数超过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)  
    }
    }

2 个答案:

答案 0 :(得分:1)

刚刚发现我的问题。我根本没有将计时器重置为计时器。首先,我试图在“动作”功能中重置它,但我只需将其移至底部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()   
    }
    }

答案 1 :(得分:0)

var timeClock =  2

由于它出现在一个类中但不在任何方法之外,因此该行声明了一个名为timeClock的类的属性,并将其初始化为2。这将是您创建的该类的任何实例的timeClock属性的起始值。

您在倒数时正确更新此值,但无法将其重置为2。将属性声明置于低于action()方法的位置并不意味着它之后会被执行。该属性仅在每个实例初始化一次。

您要做的是在计划计时器之前将timeClock的值设置为2,或者在使计时器无效之后将其设置为2。无论哪种方式,您都需要将其重置为2某处。