3

I have been trying to add a background around my SKLabelNode, but I can't figure out how to do it programmatically in swift 3. I see some old posts that use .background, but that doesn't work for me.

let background = SKSpriteNode(color: UIColor.white, size: CGSize(width: CGFloat((title.frame.size.width)), height:CGFloat((title.frame.size.height)))) 
background.zPosition = -1
background.position = CGPoint(x: self.frame.width / 12 * 6, y: self.frame.height / 12 * 11); title.addChild(background)
Fluidity
  • 3,985
  • 1
  • 13
  • 34
GS.
  • 123
  • 12

1 Answers1

3

Check this new code, I think this suited more to your problem

    let shape = SKShapeNode()
    shape.path = UIBezierPath(roundedRect: CGRect(x:(label?.frame.origin.x)! - 15, y: (label?.frame.origin.y)! - 15, width: ((label?.frame.size.width)!+30), height: ((label?.frame.size.height)! + 50 )), cornerRadius: 64).cgPath
    shape.position = CGPoint(x: frame.midX, y: frame.midY)
    shape.fillColor = UIColor.red
    shape.strokeColor = UIColor.blue
    shape.lineWidth = 5
    label?.addChild(shape)

Layout

cole
  • 3,147
  • 3
  • 15
  • 28
  • The background disappears when I add a position to it – GS. Aug 26 '17 at 20:00
  • Here's my code: let background = SKSpriteNode(color: UIColor.white, size: CGSize(width: CGFloat((title.frame.size.width)), height:CGFloat((title.frame.size.height)))) background.zPosition = -1 background.position = CGPoint(x: self.frame.width / 12 * 6, y: self.frame.height / 12 * 11); title.addChild(background) – GS. Aug 26 '17 at 20:16
  • Try this code. Sorry background.position move the background position. Also position is used when you need to be adjust it. If you are happy with my answer please up vote it. – cole Aug 26 '17 at 21:52
  • uh, shouldn't you be adding the label as a child of the background? `background.addChild(label)` – Fluidity Aug 26 '17 at 22:17
  • No, not necessarily. It wont be wrong that way either. It depend which is declare first and how you want to use it. For this question, there is no information mention, so in my answer I choose to reply this way. – cole Aug 26 '17 at 22:35
  • It works, but is there any way that I could make it rounded around the label? – GS. Aug 27 '17 at 23:48
  • 1
    don't forget to use @person... I didn't get notified of your response :) – Fluidity Aug 28 '17 at 13:56