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)?
Asked
Active
Viewed 7,700 times
12
-
If you show what you already tried, it would help us assist you. – Mick MacCallum Sep 13 '14 at 01:47
-
2Thanks 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
-
1I did...it's below. I answered the question myself. – 02fentym May 19 '15 at 21:28
3 Answers
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
-
2OK, but how do you ensure the outer (sprite) button sprite is going to be big enough for the text? – trojanfoe Apr 22 '15 at 13:31
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)
}
-
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