如何在Swift中访问GameViewController的特定实例的变量值

时间:2015-03-27 17:21:04

标签: ios swift xcode6

这是我的相关代码:

来自我的GameScene课程:

    func resetCircleAndScore(scale: CGFloat)
{
    circleIsStationary = true
    currScore = 0
    CIRCLE.speed = 1
    CIRCLE.physicsBody!.velocity = CGVector(dx: 0,dy: 0)
    CIRCLE.position = CGPointMake(midX, midY)
    circleScale = scale
    circleSpeed = CONSTSPEED
    CIRCLE.setScale(circleScale)
    currScoreLabel.text = "SCORE: " + Int(currScore).description
    //need to update modeSelected here
}

来自我的GameViewController类:

public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
    modeCopy = modes[row]

    println(modeCopy)
}

我尝试为modeCopy添加一个getter,如下所示:

public func getMode() -> String
{
    return modeCopy
}

问题在于,当我尝试从另一个类调用此函数时,它需要一个名为" self"的参数。类型GameViewController。我真正想要做的是访问创建我的GameScene的GameViewController实例。我也可以访问GameViewController创建的GameScene实例,但我不知道该怎么做。我在GameViewController中的ViewDidLoad位于下方。

override public func viewDidLoad()
{
    self.pickerView.dataSource = self
    self.pickerView.delegate = self

    println("got to beginning of viewDidLoad")
    super.viewDidLoad()

    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene
    {
        // Configure the view.
        let skView = self.view as SKView
        let showStats: Bool = true
        skView.showsFPS = showStats
        skView.showsNodeCount = showStats

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }
}

1 个答案:

答案 0 :(得分:1)

如果GameScene是你自己的类,你可以添加一个GameViewController类型的可选参数。

class GameScene {
    weak var parentController: GameViewController?

....
}

在取消归档GameView时,在viewDidLoad()方法中执行此操作

scene.parentController = self

现在你可以在GameScene中使用它了