On our journey to understanding the SwiftUI framework, we will be solving some problems in the great and splendid Mangoville, a small town that doesn’t have access to Xcode. I already got tons of requests from Mangopolitans!
Captain Shilly Shally, leader of a long-forgotten pirate gang called the Helter Skelters, needs our help. His poor pirates work night and day without rest, and after getting 3 billion dollars to free Rudolph, and swearing to never kidnap him again (don’t worry about how the pirates are going to make their money — they made no promises for Comet and Dancer), he has decided that they deserve a three-week vacation! Meanwhile, Shilly and his wife, Dilly Dally, are headed to the Bahamas to celebrate their 21st anniversary.
The only problem: Shilly is stuck, hesitant about what to get his wife as a gift. Captain Shally left us a list of gifts that he stole from Santa Claus (I got a feeling that Shilly Shally will be on the naughty list this year), and he has asked us to build him an app that will randomly pick a gift from his list.
Let’s get going!
Start by going to Xcode and adding a project. If you’re in Xcode, you will see File on the menu bar. Click File and go New > Project.
Our first step is to make a button that Captain Shilly Shally can tap to randomly choose a gift for him. Now, to add a button to your view, you can either start typing “Button” and let Auto-complete do the rest, or (my personal favorite) adding it with the little plus icon and dragging it into your code. To do that, hold it while dragging it into your body. Not YOUR body… your file’s body 😳.
Our second step is to replace the little brackets “{}” placeholder with the action parameter, which takes in a closure or a function name to run when the button is tapped. In our case, we will use a function name.
Call the function “randomize” and edit the text on your button to call it “Randomize” as well. Did you notice I’m not including the brackets beside the function name? That’s because if I do, the function will be called right away, but if I don’t, it will only be called when the button is tapped.
Now, let’s add our function outside the body (but still inside the struct). Your code should look like this:
struct ContentView: View { var body: someView { Button(action: randomize) { Text("Randomize") } } func randomize() { } }
Great! Time to get the technical part working. Go ahead and add these two variables:
let gifts = ["ShellPhone 11 Pro Max", "Aztec necklace", "Bedazzled peg leg"] @State var gift = ""
- The gifts variable is Captain Shilly Shally’s list in a String Array.
- The gift variable is what we will be passing in for our Text (basically the item getting passed into our Text for the random gift), which we will implement later. We make our variable an @State because we want it to update it each time it is called.
Next, let’s get our function working. Adding this line of code in the function will make it choose a random element from our gifts:
gift = gifts.randomElement() ?? ""
To add the text, just follow the same pattern as we did with the Button (drag the text above the button to get a better design) and replace the content of the text with our gift variable. Don’t get too excited, we still need to embed our Button and text into a VStack (otherwise we will get errors), which is basically a place to show your Views vertically.
I personally call it Mr. V, which goes perfectly with his “brothers”: H (short for HStack which allows Views to align horizontally) and Z (short for ZStack which allows Views to stack on top of each other). They’re the Stack family!
Anyways, the fastest way to embed them in a VStack is to write “VStack {” above our Text and by closing it with another bracket “}” under our Button. Your file should look like this:
import SwiftUI struct ContentView: View { let gifts = ["ShellPhone 11 Pro Max", "Aztec necklace”, "Bedazzled pegleg"] @State var gift = "" var body: some View { VStack { Text(gift) Button(action: randomize) { Text("Randomize") } } } func randomize() { gift = gifts.randomElement() ?? "" } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Next, to get an idea of what our app will look like when it actually runs, let’s get a preview of SwiftUI’s magic! (See what I did there? Preview as in the SwiftUI previews and preview as in the actual word. Never mind…) To enable SwiftUI’s Previews (basically a live-updating simulator), you simply have to click on these little lines stacked together on the top right of your Xcode window, then click Canvas.
Ta-da! Now you’ll be able to see what your app will look like when it actually runs.
What time is it? Design time! Doesn’t the button look kind of ugly right now? (If you said no, you are officially excommunicated from this web page! Just kidding.) Let’s make it look nicer by adding these modifiers to your button:
Button(action: randomize) { Text("Randomize") .padding() .foregroundColor(.white) .background(Color.red) .cornerRadius(10.0) }
- The padding gets us more space for the background color (otherwise the button will look extremely cramped).
- The foreground color is there to define the text color inside the little red box (background).
- The background color is basically a little red box under the text.
- The corner radius makes the background’s corners look like half circles.
To make our Text look better, we should add some padding to the Text (not the one inside our Button). The finishing touch is to edit our file name. To do that, command click (⌘ click) on ContentView. After that you’ll almost be done.
Now you just need to change ContentView in the comments at the top of your file to “GiftPickerView”. Your file should look like this:
import SwiftUI struct GiftPickerView: View { let gifts = ["ShellPhone 11 Pro Max", "Aztec necklace", "Bedazzled peg leg"] @State var gift = "" var body: some View { VStack { Text(gift) .padding() Button(action: randomize) { Text("Randomize") .padding() .foregroundColor(.white) .background(Color.red) .cornerRadius(10.0) } } } func randomize() { gift = gifts.randomElement() ?? "" } } struct GiftPickerView_Previews: PreviewProvider { static var previews: some View { GiftPickerView() } }
That’s all folks!
Update: If you want to test out the final result, you can download the project from my GitHub page here.
No Comments