I've implemented a counter in my app, and it works. Then, when I change of ViewController
(When i run my app), my counter reset to 0 automatically. I want my counter to continue while i'm using the app.
Thank's for your Help :)
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
}
}