繁体   English   中英

在viewcontroller上停止计时器关闭快速

[英]stoping timer on viewcontroller dismiss 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)
        }
    }

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

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)
    }
}

为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)
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM