How to Programmatically Add A Health Bar to Your iOS Game

In today’s article, we’re going to add a health bar to an iOS app entirely programmatically in Swift 5. In the process, we’ll gain experience with UIProgressView, UIImageView, GestureRecognizer, Constrains, and Animations.

By the end of this tutorial, you will have made an enemy on the screen with a health bar above its head. When you click on the enemy, it will shrink then grow through UIView animations while its health bar slowly decreases.

Code

Step 1: Create a new XCode project and then add the png image found at https://drive.google.com/drive/u/0/folders/1gBVQQp-1lb2EIdLoL106vpDWsYpofmKF to your Assets.xcassets folder.

Step 2: Creating and setting up our subviews. In your ViewController.swift file, add the following code. Here, we create a variable for the health bar and another variable for the enemy. In our viewDidLoad function, we call the setUpSubviews function which initializes and adds constraints to both the enemy and the health bar.

Step 3: Adding an animation whenever the enemy is clicked on. We first need to add a gesture recognizer to the enemy, so that our program can be informed whenever the user clicks on the enemy.

Insert this single line of code at the last line in your setUpSubviews function:

At this point, you will likely have an error from XCode stating that there is a “Use of unresolved identifier ‘hitEnemy’”, so let’s resolve this by adding the following code. In the code below, we add animations to show that the enemy has been damaged by scaling the enemy size and reducing its health.

Thanks for reading. Do you have any questions? Let me know in the comment section.

Share the article, so other developers can read it too.

I make tutorials and articles on Programming, iOS Development, and Mathematics github.com/EricGustin