Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 · Swift 5.5, iOS 15, Xcode 13

Part 2: SwiftUI Data

11. Buttons & Actions

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Introduction Next episode: 12. SwiftUI State
Transcript: 11. Buttons & Actions

At this stage, you’ve added a “Hit Me” button to Bullseye, but when you tap it nothing happens.

That simply won’t do - it’s time to add some interactivity to the app! Let’s start by making the button simply print out a text message to the console when you tap it.

Edit the code for the Button so that it looks like this:

Button(action: {
  print("Hello, SwiftUI!")
}) {
  Text("Hit me")

Build and run, and show that you now see the message in the console.

print() is an example of a function. A function is like a method, except that it’s not attached to any instance. Not being attached to a class or struct means that you can use it without having to name an instance first.

In Swift, any time you see a name that starts with a lowercase letter that’s immediately followed by parentheses, such fontWeight() or print() — you’re probably looking at the name of a function or method. The difference is that methods are preceded by the instance that you’re calling the method on, while functions don’t belong to any instance and simply appear on their own.

The print() function takes some text and then prints it in Xcode’s Console, which is the pane in the lower right of Xcode that we saw earlier.

You can think of print() as a developer’s best friend. It’s very useful as a debuging tool, which means it’s purpose is to help you figure out what’s going on in your program, and to find the cause of any bugs you may have. You only see its results in Xcode, while you’re developing the app. If you take your app and ship it to the App Store, print() has no effect. It’s there only to help you out while you’re developing.

As you continue programming, you’ll find yourself using print() as an indicator to check that specific piece of code is being executed, or to check on some value that your program has stored. In the code you just wrote, you’re using print() to make sure that you run some code when you tap the button.

The fact pressing Hit me! in your app causes print() to print “Button pressed!” in the Console is a good sign. It means that you’ve proven you can make something happen when the button is pressed. Congratulations — you’ve just written some interactive code!

But you’re not done yet. Since print() is a debugging tool, users never sees their results. From their point of view, pressing Hit me! still does nothing. You still have to make the button provide a response that the user can see. And in order to do that, we need to go over the concept of SwiftUI state.