Search code examples
iosswiftcounterviewcontroller

How to get my counter in a different Viewcontroller


I want to find back my private var currentCount : Int? which is on my main ViewController in a second ViewController (ViewController2).

But I can't catch it

After, I would like to store the value of this counter to make an "if" loop to enable and disable a button. Can anyone help me? thank you so much

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

    }
        }
 //
//  ViewController2.swift
//  PROJET X
//
//  Created by Alexis Decloedt on 22/12/2019.
//  Copyright © 2019 Alexis Decloedt. All rights reserved.
//

import UIKit




class ViewController2: UIViewController {

    @IBOutlet weak var Clue1Button: UIButton!
    @IBOutlet weak var Clue2Button: UIButton!
    @IBOutlet weak var Clue3Button: UIButton!
    @IBOutlet weak var Clue4Button: UIButton!
    @IBOutlet weak var Clue5Button: UIButton!
    @IBOutlet weak var Clue6Button: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()
        Clue1Button.isEnabled = true
        Clue2Button.isEnabled = true
        Clue3Button.isEnabled = true
        Clue4Button.isEnabled = true
        Clue5Button.isEnabled = true
        Clue6Button.isEnabled = true


        let guide = view.safeAreaLayoutGuide
        let height = guide.layoutFrame.size.height

        // Do any additional setup after loading the view.
    }

    @IBAction func ChestButton(_ sender: Any) {
        dismiss(animated: false, completion: nil)
    }

    }

Solution

  • Welcome on StackOverflow!

    I'm not sure I fully understood your problem, but if I have you need to:

    • set a variable that you're able to update from different ViewControllers;
    • store the variable's value whenever it changes;
    • check the value stored and perform an action;
      For this last step I'm not sure if you need to do it all inside a vc or two, so I'll show you how to do that with two vcs. If you need to do that just in one, please ignore the AppDelegate parts.

    AppDelegate

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    var vc1: ViewController?        //Delegate for your first VC
    var vc2: SecondViewController?  //Delegate for your second VC
    

    First VC

    //Set the delegate
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    //Declare your global variable
    var  currentCount : Int?
    //var to shorten the coding proces
    var defaults  = UserDefaults.standard
    //Key to store the value (store it outside the class to make it global so that it works wherever you want)
    let countKey = "CountKey"
    //Get the value stored thanks to userDefaults
    let currentValue = defaults.integer(forKey: countKey)
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            currentCount = 0 //Init your variable
        }
    
        func increase(){
            //Increase or decrease your variable here or in a func:
            currentCount! += 1
            //Set the value
            defaults.set(currentCount, forKey: countKey)
        }
    
        //Function to enable/ disable your button in the other vc
        func buttonStatus(){
            if currentValue == 6{
            appDelegate.vc2?.myButton.isEnabled = true
            } else {
                //...
            }
        }
    
    }
    

    Second VC

    class SecondViewController: UIViewController {
    
        @IBOutlet weak var myButton: UIButton!
        override func viewDidLoad() {
            super.viewDidLoad()
            //Print the value stored
           print("\n", currentValue)
    
        }
        //Use this just if you need to use just a view controller
        func getValue(){
            if currentValue == 6 {
                myButton.isEnabled = true
            }
        }
    
    }
    

    Please, whenever you update your counter, remember to set:

     defaults.set(currentCount, forKey: countKey)
    

    Let me know if you need more help!