简体   繁体   中英

Modify and access a var from another class in Swift

I have two Scenes and Two Swift files with two different classes. One of them called GameViewController and the other one is called FelicidadesViewController .

In GameViewController I have a Int var called round which I have initialized with the number 1. So, in the same class I have a button when I push on it, if the condition is true, appear the second viewcontroller called FelicidadesViewController .

I want to pass the var called round to the second viewcontroller and in this view sum one to the round when I push the button that I have created in this class called nextLevel .

How can I modify and access to a variable to another class in different ViewController?

You need to use prepareForSegue.

  1. Add identifier to your segue (click the arrow between two screens in storyboard and set identifier in right panel)
  2. In second VC (view cotnroller) make var round
  3. In first VC override func prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier=="yourIdentifier"){ if let nVC = segue.destinationViewController as? SecondVC{ nVC.round = self.round } } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM