12

I have an SKLabelNode that is the child of a SKSpriteNode because I'm trying to create a Button class to create buttons in an easier way. I've tried a couple of things using the anchor point of the SKSpriteNode, but I don't quite understand exactly what is going on. How do I centre the label onto the sprite (it's parent node)?

02fentym
  • 1,762
  • 2
  • 16
  • 29
  • If you show what you already tried, it would help us assist you. – Mick MacCallum Sep 13 '14 at 01:47
  • 2
    Thanks for the quick response. I actually just figured out how to do it. I set the alignment modes (horizontal and vertical) of the label and it is perfectly centred now no matter what size the label text is! I'll post below. – 02fentym Sep 13 '14 at 01:50
  • @02fentym we wish you would have showed your code solution instead of simply expounding the fact you solved a question you asked without showing the solution. – Shawn J. Molloy May 19 '15 at 16:45
  • 1
    I did...it's below. I answered the question myself. – 02fentym May 19 '15 at 21:28

3 Answers3

17

I realized how to solve this...here's what i did. Keep in mind that I have a class called Button that is a subclass of SKSpriteNode.

In the Button.m class I have an instance variable called label that is a SKLabelNode. I add the label node as a child to the button then set the horizontal and vertical alignment modes to centre.

label = [[SKLabelNode alloc] init];
[self addChild:label];
[label setHorizontalAlignmentMode:SKLabelHorizontalAlignmentModeCenter];
[label setVerticalAlignmentMode:SKLabelVerticalAlignmentModeCenter];
02fentym
  • 1,762
  • 2
  • 16
  • 29
13

This will put your label in center of scene in sprite kit:

yourLabel.horizontalAlignmentMode = .Center;
yourLabel.verticalAlignmentMode = .Center
ZygD
  • 22,092
  • 39
  • 79
  • 102
guest
  • 241
  • 3
  • 4
4

Swift 4.2 XCode 10.1

Copy this function into your SpriteKit class:

func createLabel(text: String) {

    // initialisation
    let label = SKLabelNode(fontNamed: "Wicked Mouse")

    // customisation
    label.text = text
    label.fontColor = .white
    label.fontSize = 30.0

    // positioning
    label.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
    label.verticalAlignmentMode = .center
    label.horizontalAlignmentMode = .center
    label.zPosition = 1
    
    self.addChild(label)

}
Peter
  • 29
  • 1
  • 5
Saranjith
  • 11,242
  • 5
  • 69
  • 122
  • While this might answer the authors' question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer. – Roy Scheffers Dec 31 '18 at 06:50