02fentym
02fentym

Reputation: 1772

Centre a SKLabelNode on a SKSpriteNode

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)?

Upvotes: 12

Views: 7831

Answers (3)

Saranjith
Saranjith

Reputation: 11567

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)

}

Upvotes: 4

guest
guest

Reputation: 251

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

yourLabel.horizontalAlignmentMode = .Center;
yourLabel.verticalAlignmentMode = .Center

Upvotes: 13

02fentym
02fentym

Reputation: 1772

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];

Upvotes: 17

Related Questions