2

I have searched everywhere, but I can only find how to change the UILabel fonts and can't find anywhere that teaches how to change the default SKLabelNode font. How do I do that in Xcode with swift?

I have already added the font to the Info.plist

I have also tried to add an extension that would change the default font, but it also didn't work

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
Sergio Toledo Piza
  • 793
  • 1
  • 6
  • 27
  • Just for clarification, are you looking to change the font that all `SKLabelNodes` use? Or are you looking to change a particular node away from the default? – BergQuester Feb 13 '16 at 21:26
  • I want to make the change to all of them – Sergio Toledo Piza Feb 13 '16 at 21:44
  • https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKLabelNode_Ref/ Don't much familiar with Swifty, but you could subclass it or make a category.' – Coldsteel48 Feb 14 '16 at 05:21

1 Answers1

2

Changing the font for one SKLabelNode

As you probably already know, you can change the font of a SKLabelNode using the fontName property.

let label = SKLabelNode(fontNamed:"Chalkduster")

enter image description here

label.fontName = "Arial"

enter image description here

Changing the font for all the SKLabelNode(s)

Now, if I'm not wrong you want to change the fontName for all the labels in your scene.

First of all we need an easy way to visit all the nodes in your scene graph. I mean, not only the direct children of the scene but every child of child of child...

Visiting the scene graph

The best way I can imagine is implementing a visit extension in SKNode

extension SKNode {
    func visit(logic: (node:SKNode) -> ()) {
        logic(node:self)
        children.forEach { $0.visit(logic) }
    }
}

Now SKNode has a visit function that receive a closure. The closure gets applied to the current node and to every children. Then the process is recursively repeated until there are new descendants.

Launching the recursion

Now in you GameScene you can add this code

class GameScene: SKScene {

    func changeFonts() {
        visit { (node) -> () in
            if let label = node as? SKLabelNode {
                label.fontName = "Arial"
            }
        }
    }
}

Finally, when you're ready invoke changeFonts(). It should do the job.

Just remember to use a font available in SpriteKit.

Community
  • 1
  • 1
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • 1
    I wasn't with enough time to test before, sorry. Just adding that it should be called after declaring the `SKLabelNode`s in each Scene. It worked fine, beautiful answer. Thanks! :) – Sergio Toledo Piza Feb 17 '16 at 01:47