ios - 停止 View Controller 上的计时器解雇 swift

标签 ios swift

我在 View Controller 中有一个计时器,用它来检查函数。但是,如果我关闭设置了计时器的 View Controller ,它仍然会继续,或者如果时间达到零,我想自动关闭 View Controller 。就我现在的情况而言,如果我手动关闭 View Controller 而 View Controller 没有达到零,则时间仍然会继续,直到计数器达到 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)
        }
    }

最佳答案

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

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

关于ios - 停止 View Controller 上的计时器解雇 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54765801/

相关文章:

ios - Swift - 从字符串中删除空格不起作用

ios - 点击时 iAd 横幅未加载

ios - 如何在 UICollectionViewDelegateFlowLayout 中设置无间距?

swift - 如何在 Swift 中的两个初始化函数之间共享一个初始化函数?

ios - Rxswift 结合多个可观察的奇怪行为

ios - 从 UITableViewCell 中删除除 imageView 之外的所有 subview

ios - 在 iOS 后台进行信标测距

ios - 如何将数据从两个 UITextView 保存到 UserDefaults

ios - 使用 AFXAuthClient 时,如何保留 token 并发出进一步的请求?

ios - 应用程序的通话状态栏