Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Add an Action to a Button in SwiftUI
Written by Team Kodeco

Buttons are useful when they can do something when they are tapped, clicked or pressed. In SwiftUI, you can easily add an action to a button.

Here’s how:

struct ContentView: View {
  var body: some View {
    Button("Tap Me!") {
      print("Button was tapped!")
    }
  }
}

Here’s what this will look like when you run it in the simulator:

Tap the button to see the console output.
Tap the button to see the console output.

In the code above, you create a Button with the label Tap Me! and an action that prints Button was tapped! to the console when the button is tapped. To do this, you pass a closure to the Button that is executed when the button is tapped.

You can customize the action to do anything you want, such as:

  1. Navigating to a new screen. Buttons can be used to trigger navigation to another screen or view. For example, in a restaurant app, a button can be used to navigate to the detailed view of a specific menu item.
  2. Manipulating data. You can use a button to manipulate data, such as adding an item to a shopping cart, deleting an email or favoriting a song.
  3. Changing UI elements. Buttons can change the appearance of the user interface. For example, in a weather app, a button could switch between different views such as hourly and daily forecasts.
  4. Starting and stopping tasks. Buttons can control ongoing tasks like starting or stopping a download, playing or pausing a video or refreshing data from a server.
  5. Updating state variables. In SwiftUI, a common pattern is to use a button to increment a counter or toggle a Boolean state variable, which triggers a view update.

If you prefer to use a function inside the closure, you can create a function that takes no parameters and returns nothing (Void) and call it inside the action of the button. Here is an example:

struct ContentView: View {
  var body: some View {
    Button("Tap Me!") {
      buttonTapped()
    }
  }

  func buttonTapped() {
    print("Button was tapped!")
  }
}

In this example, you create a buttonTapped function that prints a message to the console. You then call the buttonTapped function inside the action of the Button. This can help keep your code organized and make it easier to reuse the same function in different parts of your app.

In summary, adding an action to a button in SwiftUI is easy. You can use a closure or a function and customize the action to do anything you want.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.