0

I'm a newbie to OS X programming. I'm building a simple game for Mac with Sprite-Kit, and stuck with the problem of adding NSButton (and other NSObjects) to the view. It just doesn't work - no button shows up. My code:

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

How could I fix it?

P.S. I tried to add a layer to my view, as some bloggers recommended, in this situation the button actually does show up but the screen turns completely black or renders only glitches.

let layer = CALayer()
self.view!.layer = layer
self.view!.wantsLayer = true
Derreck
  • 383
  • 1
  • 4
  • 10
  • http://stackoverflow.com/questions/19082202/setting-up-buttons-in-skscene – Brendan Miller May 26 '16 at 02:09
  • 1
    As the link Brendan Miller gave you states, it's probably better to create buttons directly with SKSpriteNode objects. I don't know how SKView works under the hood, but it's likely that you shouldn't try to add any subview or work with layers on that view. – Pop Flamingo May 26 '16 at 08:09
  • The problem is - yes, I could use some simple rectangular SKShapeNodes or other elements to replace NSButtons but I need some kind of a slider, and I don't know how I could get it. I'm building game for OS X so UISlider is closed to me, and I can't figure out how to add visible NSSlider to the view. – Derreck May 26 '16 at 11:48

1 Answers1

0

OK, finally I figured out how to do that (don't need to assign a layer to your view if self.view!.wantsLayer is equal to "true"):

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)
Derreck
  • 383
  • 1
  • 4
  • 10