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

标签 ios swift xcode6

这是我的相关代码:

来 self 的 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
}

来 self 的 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)
    }
}

最佳答案

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

class GameScene {
    weak var parentController: GameViewController?

....
}

在解压 GameView 时在 viewDidLoad() 方法中执行此操作

scene.parentController = self

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

关于ios - 如何在 Swift 中访问特定 GameViewController 实例的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29306542/

相关文章:

ios - 如何在 SwiftUI 中创建多行 TextField?

ios - UINavigationController 图像未在所有 iOS 设备上居中

ios - 在同一个 ViewController 中打开文本文件

ios - 无法在 iOS 模拟器中运行我的 Apple Watch 应用程序

xcode - 需要帮助快速将音频文件添加到按钮

ios - 使用分页显示 UICollectionView 的正确方法

iOS : passing data between viewController (destination embedded in a NavigationController)

iphone - UIActivity子类打开webview

ios - Swift3 中心 UIbutton

ios - 在 Xcode 6 beta 5 中使用 'po' 命令调试选定 View