Search code examples
iosswiftsprite-kitsklabelnode

Way to know the width of the text in SKLabelNode


Is there a way to know the width of a "SKLabelNode" in Sprite Kit ?

OR I should use SKSpriteNode then use text inside it


Solution

  • Because SKLabelNode is a subclass of SKNode, and SKNodes have a frame, you can query this and get the size of the SKLabelNode:

    from the docs:

    The frame is the smallest rectangle that contains the node’s content, taking into account the node’s xScale, yScale, and zRotation properties. Not all nodes contain content of their own.

    https://developer.apple.com/reference/spritekit/sknode/1483026-frame

    Here's some of the convenient properties, of a pretend englishLabel

    englishLabel.frame.maxX
    englishLabel.frame.midX
    englishLabel.frame.minX    
    englishLabel.frame.width