0

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

    }
koen
  • 5,383
  • 7
  • 50
  • 89
  • 1
    The answer depends on how you present the second view controller in the first and how you go back. – vadian Dec 23 '19 at 17:07
  • As @vadian already said, how are you presenting/pushing `ViewController2`? The answer - didn't downvote it - is correct... nothing in your code says how the second VC is shown. In fact, it *appears* that VC1 has not `IBOutlets` where VC2 does? The issue is that - how are you (in technical terms) **navigating** fbetween these two view controllers? –  Dec 23 '19 at 17:52
  • Thank's @vadian and dfd for your answers. I'm a beginner so please be indulgent;) To make the two VC communicate, i went directly in my MainStroyboard, I selected the button i needed, right click on it and then attached this button to the second VC. Is that not a segue? – Alexis Decloedt Dec 23 '19 at 19:04

2 Answers2

1

It doesn't look like you are using a segue to transfer the information to the second view controller.

It also looks like you made the variable private. By using a private variable you are unable to access the variables value outside of the class scope. Meaning you cant access the variable from your second view controller.

Remove private from your variable name

So it’s just

var currentCount: Int?

Accessing variables from another ViewController in Swift

Following the link above will help you

Julian Silvestri
  • 1,970
  • 1
  • 15
  • 33
1

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!

  • Hi @Marybnq , thank's a lot for your help ! I'll try your solution right now. i'm a beginner and have many questions. How can i contact you for potential other questions ? – Alexis Decloedt Dec 23 '19 at 22:08