更改ViewController后计数器重置为零

问题描述 投票:0回答:2

我快速向您解释我的问题。我已经在我的应用程序中实现了一个计数器,它可以正常工作。然后,当我更改ViewController时(运行我的应用程序时),我的计数器自动重置为0。我希望我的计数器在我使用该应用程序时继续。感谢您的帮助:)

import UIKit

class ViewController: UIViewController
{
    /// Label
    private var customLabel : UILabel?

    /// MAximum Count to which label will be Updated
    private var maxCount : Int?
    /// Count which is currently displayed in Label
    private var currentCount : Int?
    /// Timer To animate label text
    private var updateTimer : Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        customLabel = UILabel()
        customLabel?.textColor = .white
        customLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 25)
        customLabel?.textAlignment = .center


        /// Add label to View
        addConstraints()

        /// Start Timer
        DispatchQueue.main.async {
            self.maxCount = 600
            self.currentCount = 1
            self.updateTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(ViewController.updateLabel), userInfo: nil, repeats: true)
        }
    }

    @objc func updateLabel() {
        self.customLabel?.text = String(currentCount!)
        currentCount! += 1
        if currentCount! > maxCount! {
            /// Release All Values
            self.updateTimer?.invalidate()
            self.updateTimer = nil
            self.maxCount = nil
            self.currentCount = nil
        }
    }

    func addConstraints(){
        /// Add Required Constraints
        self.view.addSubview(customLabel!)
        customLabel?.translatesAutoresizingMaskIntoConstraints = false
        customLabel?.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 195).isActive = true
        customLabel?.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50).isActive = true
        customLabel?.heightAnchor.constraint(equalToConstant: 50).isActive = true
        customLabel?.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 310).isActive = true
    }
}
swift xcode timer count reset
2个回答
0
投票

实际发生的情况是,每当您回到ViewController时,您都在创建一个新计数器。您需要做的是在viewDidLoad()外部声明您的计数器,但请确保您的ViewController是应用程序的根ViewController,并且永远不要将其初始化否则您的应用将崩溃。


-1
投票

使用结构来存储和获取这样的值:

struct MyCounter {
    static var counterValue = 0
}

然后您可以像这样使用它:

MyCounter.counterValue = 20
© www.soinside.com 2019 - 2024. All rights reserved.