更改变量并将其发送到第二个视图控制器

时间:2016-10-20 21:29:30

标签: ios swift function uiviewcontroller

我正在为我的游戏创建一个商店屏幕。你可以在哪里买角色。当在商店视图上按下按钮然后将其发送到下一个视图控制器时,我需要一个变量来更改。然后第二个视图控制器将根据变量的值选择正确的播放器我有以下商店视图控制器的代码:

import Foundation
import UIKit

class Shop: UIViewController {

    @IBAction func buttonPressed(_ sender: AnyObject){
        var x = 1
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "segue") {
            let dest = segue.destination as! GameViewController
            dest.x = x
        }
    }
}

但变量不是全局的,所以我该怎么做。任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

根据您的要求,我相信全局Singleton对象是您的最佳选择。

全局单例将允许您跨控制器访问您的商店数据。

E.g。

class ShopManager {
    static let sharedInstance = ShopManager()

    var x = 0 // some initial value

    private init() {} //Ensures singleton is unique
} 

现在您可以在任何地方获取/设置ShopManager.sharedInstance.x(或在单例类中声明的任何其他变量/对象),而无需在控制器之间传递数据。

import Foundation
import UIKit

class Shop: UIViewController {

    @IBAction func buttonPressed(_ sender: AnyObject){
        ShopManager.sharedInstance.x = 1
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "segue") {
            let dest = segue.destination as! GameViewController
            //no need to set dest.x here. just access ShopManager.sharedInstance.x from the destination controller!
        }
    }
}

class ShopManager {
    static let sharedInstance = ShopManager()

    var x = 0 // some initial value

    private init() {} //Ensures singleton is unique
} 

答案 1 :(得分:0)

  1. 您可以将x存储为ShopViewController
  2. 中的变量

    var x: Int?
    
    @IBAction func buttonPressed(_ sender: AnyObject){
        x = 1
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "segueId") {
            let dest = segue.destination as! GameViewController
            dest.x = x
        }
    }
    
    1. 您可以add a segue from one controller to another代替确切的按钮,然后通过回调执行此操作:
    2. @IBAction func buttonPressed(_ sender: AnyObject){
          performSegue(withIdentifier: "segueId", sender: 1)
      }
      
      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if (segue.identifier == "segueId") {
              let dest = segue.destination as! GameViewController
              dest.x = sender as! Int
          }
      }