我是 OS X 编程的新手。我正在使用 Sprite-Kit 为 Mac 构建一个简单的游戏,但遇到了向 View 添加 NSButton(和其他 NSObject)的问题。它只是不起作用 - 没有按钮显示。 我的代码:
class LaunchScene: SKScene {
override func didMoveToView(view: SKView) {
let background = SKSpriteNode(imageNamed: "Wall")
background.size = CGSize(width: 1600, height: 1200)
background.position = CGPoint(x: CGRectGetMidX(self.frame),
y: CGRectGetMidY(self.frame))
self.addChild(background)
let button = NSButton(frame: NSRect(x: self.frame.width/2,
y: self.frame.height/2, width: 50, height: 25))
self.view!.addSubview(button) //button doesn't show up
我该如何解决这个问题?
附注我尝试在我的 View 中添加一个图层,正如一些博主建议的那样,在这种情况下,按钮实际上确实显示了,但屏幕完全变黑或仅呈现故障。
let layer = CALayer()
self.view!.layer = layer
self.view!.wantsLayer = true
最佳答案
好的,最后我想出了如何做到这一点(如果 self.view!.wantsLayer 等于“true”,则不需要为您的 View 分配图层):
class LaunchScene: SKScene {
override func didMoveToView(view: SKView) {
let background = SKSpriteNode(imageNamed: "Wall")
background.size = CGSize(width: 1600, height: 1200)
background.position = CGPoint(x: CGRectGetMidX(self.frame),
y: CGRectGetMidY(self.frame))
self.addChild(background)
self.view!.wantsLayer = true
let button = NSButton(frame: NSRect(x: self.frame.width/2,
y: self.frame.height/2, width: 50, height: 25))
self.view!.addSubview(button)
关于swift - 无法将 NSButton 添加到 Sprite-Kit 场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37450021/