Creating a HUD for your Sprite Kit Game

Creating a HUD for every game is vital.
It’s a bit tricky when you are adding UI Elements to Sprite Kit and there are also
a few different ways of doing it.
Here is one of the ways and so far my favorite.
It’s very flexible and it will allow you to easily customize your code later on.
For the purpose of this tutorial we’ll create a SpriteKit Scene with a label in the middle and
then we’ll add a HUD that will only have a UISwitch, which when switched will change our label in the scene. It’s very simple ,but you can build up on top of that and create more complex HUDs for your needs.

We’ll start by creating a new project.

Disable the portrait:

We want to remove the default logic from the GameScene file that places a spaceship wherever you
tap. We’ll also change the label a bit.
Open the GameScene.swift and replace all the content with the following:

Now we’ll create 2 more files:


It’s my personal practice that I like doing and I feel is helping me organize my projects.
In global.swift we’ll keep all global parameters and in functions we’ll keep any functions that would be shared between different classes in the project.

For now just put this in global.swift:

In functions.swift just place this:

Next we gotta prepare the HUD.
Basically the HUD will consist of 3 things.
The UIView that we are going to see, the file that describes the UIView and another file
that helps load the UIView.

Create a new file => UIView , and name it hud:

Now create 2 .swift files:


Open hud.swift and replace the content with the following:

At this point if you run the project you should see a gray screen with the label ‘fruit’ in the middle. Good.
Now we have to define our custom classes.
Select the hud.xib and inside once you have selected the View, click on File Owner and
change the class to ‘hud’ – this is how we are going to load the view from nib.

Then click on the View below, change the class to hudSetup and change the background color to black.

Drag a UISwtich to the view and just position it towards the top, middle of the screen.
Add the missing constraints:

Next drag the UISwitch with your right mouse button to the hudSetup.swift file to
create the IBAction for it.
At the end you should have this in the hudSetup.swift:

Notice that we are referencing to our global function here.

Now open the GameScene.swift and add this function at the bottom right before the last

Then right after the frameW and frameH in the didMoveToView { }, add this:

This is going to create our symbolic HUD with the switch inside.

With this we should be all set.
Once you run the app you should see the HUD with the switch in the top left corner and
when you switch it the label will cycle between ‘fruit’ and ‘veggies’.

That’s all for this tutorial.
If you have any questions or recommendations, please leave us a comment below. Thank you!