Creating Your First App using SwiftUI in Playgrounds

This is a small tutorial that I use with a variety of students, educators, and leaders to demonstrate how to build a small but useful app using SwiftUI on the iPad with Swift Playgrounds. This tutorial can also be used on the Mac as well as in Xcode with some minor adaption.

I begin the session by introducing the key ideas of what SwiftUI is, i.e., a toolbox to pull prebuilt structures and code to build the app. 

We then explore the three different kinds of stacks that can be used in this app: VStack (Vertical), HStack (Horizontal), and ZStack (Layered).

   

 
 

Following this, we explore what changing the code inside the stack does by inserting two colors for our flashlight. Note: I tend to use black and yellow as these colors will both display, even when the app is in light/dark mode. I do not recommend starting with white for this reason (unless in dark mode).

 

After changing the VStack to a ZStack, we will then explore the process of adding a variable and logic statement (true/false) to connect the status of the app with the state of the flashlight. The variable (var) we introduce is going to be called "isLightOn". You could technically name this variable anything but this is descriptive and so I use this to keep things simple. Additionally, we start in the state of false to indicate that we want the flashlight to be "off" by default. Thus, if you change the statement to true, the flashlight would be in the "on" position by default.

 

It is important to point out at this point that code is read from left to right and top to bottom. This helps to explain why the black color is hiding the yellow color.

Next, we will introduce the concept of an if statement. I like to connect this to the idea of "If You're Happy and You Know It". This helps people to see the connection between turning the light on and off. (See Image below)

 

Finally, I introduce dropping a toggle from the prebuilt SwiftUI bricks. Once that is inserted inside the ZStack, we add the variable isLightOn. We will get an error that tells us to place a "$" in front of our variable. This is important because the $ locks the state of the app to the toggle. (See images below)

 

 
The last step that we do to finalize our product is to hide the label from the toggle. This is important because if will center our toggle into the middle of the app. Additionally, we will add some code that ignores the top and bottom "safe space" for the battery indicator, time, etc. This helps to prevent the flashlight from having white on the screen when the light is "off".

 

 

In addition to these pictures and walk through, I am attaching my annotated version of the flashlight app that can be opened in both swift playgrounds and Xcode.



Attachments

There are no replies.