SwiftUI button trigger event handle

In this tutorial, you are going to learn how to handle an event action of a SwiftUI button when it is triggered by the user.

We all know that users of Apple devices often have to interact with buttons inside the app in daily life. A common usage is to perform some action when click the button. So, in this tutorial, you will see executing the Swift code when triggering a button.

Below is the simple way to handle an event when a button is triggered:

Button(action: {
    // Code to execute
}) {
    // Looks of the button

In the above program, the code inside action will execute when the user click the button.

Now let’s see a complete Swift code where we actually print some text in Xcode terminal when a button triggered:

Button(action: {
    debugPrint("Button clicked")
}, label: {
    Text("Click Me")

In the above code, we have set the button text “Click Me”. Now to test it let’s click or trigger the button and see if you can see the “Button clicked” message in console.

If everything goes right, you can see the text “Button clicked” in the debug log whenever the button triggered or click.

Below is what you can see when clicking the button 3 times:

Button clicked
Button clicked
Button clicked

That’s it… We have succussfully able to detect button triggered in SwiftUI.