0
votes

I have some vars in my Main VC and when user clicks a button in another VC the prepareForSegue passes along a new value to the Main VC and updates a label.

But when the user clicks again it's back to initial value, so it doesn't increment since the value is set back in the viewDidLoad?

MainVC:

var statsHealth:Int = 0

override func viewDidLoad() {
    super.viewDidLoad()

    healthLabel.text = String("Health: \(statsHealth)/10")

}

Another VC:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "startSegue") {

        let startVC = segue.destinationViewController as ViewController

        startVC.statsHealth += 1

    }

It's displayed as 0, then 1 but then 0 again and then 1 instead of 2,3,4 etc.

Any ideas?

BR

Nils

2

2 Answers

1
votes

So based on your description, I assume the view controller structure is like this:

AnotherVC -> MainVC

MainVC is presented on top of AnotherVC. When you go back to AnotherVC, did you dismiss MainVC completely? If so, then every time you go from AnotherVC to MainVC, it initiate a new ViewController, and the variables you saved before doesn't exist anymore.

If you want to keep this structure and change variables in MainVC, keep a reference of mainVC in AnotherVC. Then instead of connecting in storyboard, you may want to present it programmatically.

class AnotherVC {
    var mainVC: MainVC?

    func presentMainVC() {
         var targetVC = UIViewController()
         if self.mainVC != nil {
             targetVC = self.mainVC

         } else {
             let storyboard = UIStoryboard(name: "Your-storyboard-name", bundle: nil)
             targetVC: MainVC = storyboard.instantiateViewControllerWithIdentifier("The-main-VC-identifier") as MainVC
             self.mainVC = targetVC
         }

         //you can change your variable here
         mainVC.statsHealth += 1

         self.presentViewController(self.mainVC, animated: true, completion: nil)
    }

If you mainVC is on top of AnotherVC in any case, you can just revert the reference direction.

1
votes

Perhaps not the most 'Swift' way to do it, but certainly works well....

Create a file called Variables.swift which will hold all your 'universal' variables (if these are going to be on every page, I see no reason this isn't the 'best' way to do it - certainly it is the most simple to understand!)

in Variables.swift, hold all your universal variables

struct Variables {
    static var statsHealth = 0
.....
}

Then, in each other page, access them at any time

 healthLabel.text = String("Health: \(Variables.statsHealth)/10")

or set them

Variables.statsHealth += 1