在ViewController上停止计时器可消除swift

时间:2019-02-19 11:57:17

标签: ios swift

我在视图控制器中有一个计时器,用于检查功能。但是,如果我关闭设置了计时器的Viewcontroller,它仍然继续,或者如果时间到零,我想自动关闭Viewcontroller。在我现在的情况下,如果我在视图控制器未达到零的情况下手动关闭视图控制器,则时间仍将持续到计数器达到ero为止。

我该如何设置代码,以便如果我自己解雇Viewcontroller,时间将停止并且不会达到零,因此如果时间为零,我所放置的条件将不会运行。

下面是我的代码

override func viewDidLoad() {
        super.viewDidLoad()

        var _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

        timerLabel.text = "\(counter)"
    }


    @objc func updateCounter() {
        //you code, this is an example
        if counter >= 0 {
            timerLabel.text = "\(counter)"
            counter -= 1
        }

        if counter == 0 {

            Print.HOMEPRINT("COUNTER GOT TO ZERO")

            dismiss(animated: true, completion: nil)
        }
    }

2 个答案:

答案 0 :(得分:0)

为计时器声明一个公共变量,然后在要停止时使其无效。

var timer : Timer?

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

    timerLabel.text = "\(counter)"
}


@objc func updateCounter() {
    //you code, this is an example
    if counter >= 0 {
        timerLabel.text = "\(counter)"
        counter -= 1
    }

    if counter == 0 {
        timer?.invalidate()
        Print.HOMEPRINT("COUNTER GOT TO ZERO")

        dismiss(animated: true, completion: nil)
    }
}

答案 1 :(得分:0)

为Timer创建全局变量

var myTimer : Timer?

override func viewDidLoad() {
    super.viewDidLoad()

    myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

    timerLabel.text = "\(counter)"
}


@objc func updateCounter() {
    //you code, this is an example
    if counter >= 0 {
        timerLabel.text = "\(counter)"
        counter -= 1
    }

    if counter == 0 {
        if (myTimer != nil)
        {
          myTimer?.invalidate()
          myTimer = nil
        }
        Print.HOMEPRINT("COUNTER GOT TO ZERO")

        dismiss(animated: true, completion: nil)
    }
}

// MARK:手动关闭控制器

    @objc func dismissButtonTapped()
    {
    if (myTimer != nil)
            {
              myTimer?.invalidate()
              myTimer = nil
            }
    dismiss(animated: true, completion: nil)
    }