Macos 将NSButton与SpriteKit一起使用

Macos 将NSButton与SpriteKit一起使用,macos,cocoa,swift,Macos,Cocoa,Swift,我是一名tyro Cocoa程序员,试图通过修改默认的OSX代码来了解Swift/Cocoa/SpriteKit。所以这可能是一个基本的问题,但我还没有找到解决办法 我想添加功能来删除你用鼠标点击后得到的所有飞船精灵,所以我将这些方法添加到类:GameSecene override func keyDown(theEvent: NSEvent!) { if (theEvent.characters) == "p" { removeSprites() } } fu

我是一名tyro Cocoa程序员,试图通过修改默认的OSX代码来了解Swift/Cocoa/SpriteKit。所以这可能是一个基本的问题,但我还没有找到解决办法

我想添加功能来删除你用鼠标点击后得到的所有飞船精灵,所以我将这些方法添加到类:GameSecene

override func keyDown(theEvent: NSEvent!) {
    if (theEvent.characters) == "p" {
        removeSprites()
    }
}

func removeSprites() {
    self.removeAllChildren()
    println(self)  // Here to track down my problem.
}
因此,当我按下“p”键,并且
println(self)
告诉我
self
name:'(null)帧:{{0,0},{1024,768}


接下来,我在Interface Builder的SKView中设置了一个NSButton,并将其连接到
class:AppDelegate

@IBAction func buttonAction(sender: AnyObject) {
   GameScene().removeSprites()
    }
然而,这次精灵并没有被移除,println报告

<SKScene> name:'(null)' frame:{{0, 0}, {1, 1}}
name:'(null)帧:{{0,0},{1,1}
所以我对这个“另一个”场景感到困惑

如何对NSButton进行编码以产生精灵效果?

GameSecene()是类的新实例,而不是“self”在前面的方法中所指的实例

您的iAction在AppDelegate中,而不是在游戏场景中,因此您需要保留对场景的引用-如果您使用的是默认模板,则在ApplicationIDFinishLaunching中应该有对它的引用。。。把它作为一个属性,然后你可以说self.scene!。在操作中移除prites()

var scene: GameScene? = nil

func applicationDidFinishLaunching(aNotification: NSNotification?) {
    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
        self.scene = scene 
        // ...
    }
}
@IBAction func buttonAction(sender: AnyObject) {
    self.scene!.removeSprites()
}

啊!!我现在明白了。这很好用。非常感谢。