Home » Blog » How to create your first iOS App with Swift 5.1 – Lightbulb App – Full Guide

How to create your first iOS App with Swift 5.1 – Lightbulb App – Full Guide

In this article, we’ll show you exactly how to build an iOS app. No experience is required for this project.

Here is how the final app will look:

Here’s what you will need to follow along:

  • A computer running macOS (preferably macOS Catalina or macOS Big Sur; this article works for both Apple Silicon Macs and Intel Macs, but not iPads)
  • The latest compatible version of Xcode Installed (the latest version is Xcode 12 at the time of this article)
  • That’s it!

Part 1: Setup
In this part, you will configure the settings for your app in Xcode.

Start by opening up Xcode. You’ll see a screen that looks similar to the one below. Click “Create a new Xcode Project”


Once you click create, you should see a screen similar to the one below:

If it is not already selected, click iOS in the menu at the very top, and select “App” (This was called “Single-View Application” in older versions of Xcode). This step is important. You may get confused later on if you do not correctly configure this. Click next once you are done.

Once you click next, you will be presented with a number of options. These are very important, so pay attention!
1. In the product name section, enter any name you would like. This will be the name shown below the app’s icon on the homescreen. It is preferred that you use a name that is somewhat related to the app’s function (in this case, turning on and off a virtual lightbulb).
2. You can leave the Team Name “None” for now (we’ll adjust it later on).
3. In the organization identifier you can type in either of the following:
• If you have a website, enter it in reverse (ex. if xalting.com is your website, enter com.xalting in the organization identifier).
• If you do not have a website, you can enter com.[Any name you want]. Replace the part in square brackets with anything you want (such as your name or your pet’s name).
4. Make sure the dropdown next do Interface is set to Storyboard. It is set to SwiftUI by default, but we will be using storyboards as they are more straightforward.
5. Make sure the dropdown next to Lifecycle is set to UIKit App Delegate.
6. Make sure the Language is set to Swift.
7. Make sure CoreData is unchecked. You can either enable or disable the Include Tests checkbox (it does not really matter for this app).
You can now click next and you will see something similar to below.

Choose a place to save the project and click create. Preferably save it in a folder called Xcode within the documents folder to keep things organized. You should see something similar to the screenshot below once you click create.

In the case that this is not what you see after clicking create, try clicking each of the small triangles in the toolbar on the far right.

Part 2: User Interface Setup
In this section, you will set up the user interface in Xcode, using storyboards.

Start by clicking Main.storyboard in the toolbar to the very right.

You should see something similar to the screenshot below:

Using storyboards, we can drag and drop elements into the app. Unlike in Android Studio, the UI builder in Xcode is extremely powerful and can meet the needs of almost any app. Many apps on the app store are made using storyboards, however larger organizations often opt to write XML instead as it is harder to collaborate in storyboards.

Anyway, there should be a mock iPhone onscreen. If you cannot see the entire mock iPhone, try resizing the toolbars to the left and right. To zoom out, hover your cursor over the mock iPhone and do the pinch gesture if you have a trackpad or press alt and scroll if you have a mouse (or option and scroll if you are extremely modern). Also, there should be an arrow pointing to the mock iPhone. This arrow signifies that this mock iPhone will be the first screen displayed in the app after launch. Officially, these “mock iPhones” are called viewControllers, so we will refer to them as such for the duration of this article.

Next, we’ll add the first element to the viewController. To do this, simply click the plus icon on the top left:

Once you click it, you will see a menu pop up similar to the one below:

We will start by adding the toggle button, which should be one of the first items in the list. If it is not, just search for “button” and you will see it.

Now just drag the button into the viewController:

If you look at the image of the final product, you’ll see that there is text above the button that indicates whether the bulb is on or off. To add this to the app, we need to use something called a label. A label simply displays text in the app. To add this element, click the plus sign again and drag the label into the viewController.

Finally, we need to add an image of the lightbulb. We do this using an element called an imageView, which displays an image. Click the plus icon again and type “imageView” in the search bar. You should see the image view show up. Simply drag this into the viewController.

Now that everything is in place, we need to adjust the sizes of the elements to make it look more tidy.

You should have something similar to the screenshot below.

Finally, the UI is ready! Not so fast. If you look at the bottom, you will see the type of iPhone you placed the elements on. However, the elements get messed up when you change the type of iPhone.

Of course, we are not going to adjust the elements for each type of iPhone/iPad individually (that is a huge waste of time). Instead, we are going to use constraints. More specifically, we’ll use the pin tool which, according to Apple “lets you quickly define a view’s position relative to its neighbors or quickly define its size.” Confused? Don’t worry, this will make more sense as we proceed.

We will start by constraining the button. To do this, select the button and click the pin tool, which looks like this:

A menu similar to the screenshot below will pop up.

In the section at the top, click the red dotted lines next to the text box on the left, the textbox on the right, and the textbox on the bottom. The dotted lines will become solid when clicked. Also, ensure Constrain to margins is unchecked.

Change the values in the bottom, left, and right textboxes to 20, 10, and 10 respectively. This ensures that on any device, the label will be 20 points above the bottom of the device, 10 points from the left side of the device, and 10 points from the right side of the device. Do not touch the top textbox and ensure that the red lines below it are unselected (i.e. they are still dotted lines).

Check the box next to height and make sure the value is 30. This ensures that the height of the textbox will remain the same (30 points) on any device.

Finally, click “Add 4 Constraints” at the bottom.

Here is an animation of these steps:

Now, click the label and repeat these steps. Here is an animation:

Finally, we need to constrain the imageView. Click the imageView and then click the pin tool.

Constrain the imageView as follows:

Notice that we are not constraining the height this time, but we are adding a pin to all four corners. Also, notice that it says “Spacing to nearest neighbor”. In the case of the imageView, the nearest neighbor to its top, left, and right corners is the edge of the screen, and the image will be positioned 20 points away from each of these edges. However, the nearest neighbor to the bottom of the imageView is the label, so the imageView will be placed 20 points away from the top of the label.

Here is an animation for constraining the imageview:

If constraints do not make sense, you can always find explanations online, such as this one.

Almost done, but a few things are still missing.

First of all, we need to add the lightbulb images to Xcode.

Go ahead and download them here:

Open your downloads folder in Finder (the app on the far left of the dock) and locate the ZIP file. Once you find it, double click to expand.

In Xcode, open Assets.xcassets in the toolbar to the right.

Simply drag and drop the on and off images into the second-to-last toolbar.

Next, go back to the Main.storyboard file in Xcode.

Click the imageView and go to the Attributes Inspector. The attributes inspector is the icon with three sliders stacked on top of each other:

In the toolbar at the very right, set the Image to off:

Here is an animation of these steps.

Next, click the label and go to the Attributes Inspector, set the alignment to centered, and set the text to “OFF”:

Finally, click the button and set its title to “Toggle.”

Click anywhere outside the viewController.

The UI setup is now complete.

Part 3: Connecting UI to code

Run the app at its current state in the simulator by clicking the play button. Pick any iPhone as your simulator.

You’ll see something like this after it loads completely (be patient if you have a slow computer):

However, when you click toggle, nothing happens!! This is where the code comes in. Before we can start coding, we need to connect each element in the storyboard file to the code file.

To do this, start by clicking this button:

Next, click ViewController.swift; this is the code file.

You may need to click the storyboard again for the viewController to reappear. You may also need to zoom out (pinch on trackpad, alt+scroll (or option+scroll) on mouse).

Yet another animation:

Connecting the elements is easier to explain in a video, so here is a short clip on how to connect the elements in the storyboard to your code. Important: you need to right click and drag the elements. This is not very clear in the clip.

Please pay close attention to the instructions in the clip.

Part 4: Code!

Finally, we can start adding in the code!

Click the X button next to the storyboard file:

This will give you more room to write code:

At its current state, your code should look similar to this:

//
//  ViewController.swift
//  Xalting Lightbulb
//
//  Created by Xalting.com on 3/11/21.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var statuslabel: UILabel!
    @IBOutlet weak var bulbimage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func togglebtn(_ sender: Any) {
    }
    
}

Here is some explanation about what is going on:
Each line that is preceded by // is a comment. Comments do not do anything within the code and are present only to help make the code understandable. When you type //, Xcode knows that it is a comment and ignores it. If you do not place // before a comment, Xcode will think it is code and will try to execute it, which could result in an error. The comments present here were auto-generated, and you can remove them if you would like.

The first line after the comments is “import UIKit.” UIKit is a framework that allows us to work with UI elements in the code. If you try deleting the “import UIKit,” you will be attacked with errors because much of the code present relies on UIKit.

After this is the ViewController class, which is linked to the viewController in Main.StoryBoard. We can control UI elements within this class.

There are two IBOutlets within the class. These were created by Xcode and this allows us to control the image and the label within the code.

Next, the viewDidLoad() function executes code within it the first time the viewController is loaded when the app is launched. Here is where you would do any initial setup. However, for this app we do not need to do anything in this function.

Finally, there is an IBAction function that is linked to the button. This function is executed when the button is pressed. We will be using it extensively.

Enough explanation, time to get to the actual code…

Start by adding a variable called “bulbIsOn” and setting it to false. Add this right below the class.

...
class ViewController: UIViewController {
var bulbIsOn = false
...

The … indicates that there is code above and below.

Next, we will add an if/else statement inside the IBAction function that checks whether the variable bulbIsOn is true or false.

    @IBAction func togglebtn(_ sender: Any) {
        if bulbIsOn == true {
            
        } else {
            
        }
    }

If bulbIsOn is true and the button is pressed, we need to do the following:
• Set the image to the “off” lightbulb
• Set the text in the label to “OFF”
• Set bulbIsOn to false
If bulbIsOn is not true (it is false), we need to do the opposite:
• Set the image to the “on” lightbulb
• Set the text in the label to “ON”
• Set bulbIsOn to true

Here is how to do this in code:

    @IBAction func togglebtn(_ sender: Any) {
        if bulbIsOn == true {
        bulbimage.image = UIImage(named:"off")
        statuslabel.text = "OFF"
        bulbIsOn = false
        } else {
        bulbimage.image = UIImage(named:"on")
        statuslabel.text = "ON"
        bulbIsOn = true
        }

    }

We changed the image inside the imageView using this syntax:

[name of imageview IBOutlet].image = UIImage(named:"[imagename]")

In this case the name of the imageView was bulbimage and the image name was either “on” or “off.”

Similarly, we changed the text inside the label using this syntax:

 [name of label IBOutlet].text = "[text]"

In this case the name of the label was statuslabel and we changed the text to either “ON” or “OFF.”

In all, the function changes the text of the label and the image of the imageView to the opposite of what it currently is.

Here is the final code.

//
//  ViewController.swift
//  Xalting Lightbulb
//
//  Created by Xalting.com on 3/11/21.
//

import UIKit

class ViewController: UIViewController {
    var bulbIsOn = false
    @IBOutlet weak var statuslabel: UILabel!
    @IBOutlet weak var bulbimage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func togglebtn(_ sender: Any) {
        if bulbIsOn == true {
        bulbimage.image = UIImage(named:"off")
        statuslabel.text = "OFF"
        bulbIsOn = false
        } else {
        bulbimage.image = UIImage(named:"on")
        statuslabel.text = "ON"
        bulbIsOn = true
        }

    }
    
}

If you run the code now by clicking the play button at the top left, you will get a working app!

Here is how it should look and work:

If you have any questions or concerns, just comment or email info@xalting.com.

Download Final Project:

1 thought on “How to create your first iOS App with Swift 5.1 – Lightbulb App – Full Guide”

Leave a Reply

Your email address will not be published. Required fields are marked *