简体   繁体   English

在 Swift 中修改和访问另一个类的 var

[英]Modify and access a var from another class in Swift

I have two Scenes and Two Swift files with two different classes.我有两个场景和两个带有两个不同类的 Swift 文件。 One of them called GameViewController and the other one is called FelicidadesViewController .其中一个称为GameViewController ,另一个称为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 .GameViewController我有一个名为roundInt GameViewController ,我用数字 1 对其进行了初始化。因此,在同一个类中,当我按下按钮时,我有一个按钮,如果条件为真,则出现名为FelicidadesViewController的第二个视图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 .我想将称为round的 var 传递给第二个视图控制器,并在此视图中,当我按下我在此类中创建的名为nextLevel的按钮时,将一个 sum 与round nextLevel

How can I modify and access to a variable to another class in different ViewController?如何在不同的 ViewController 中修改和访问另一个类的变量?

You need to use prepareForSegue.您需要使用 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在第二个 VC(查看 cotnroller)中进行 var 回合
  3. In first VC override func prepareForSegue在第一个 VC 覆盖 func prepareForSegue

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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