The Button view in SwiftUI allows you to create interactive button elements in your app. There are two ways to declare a Button:

  1. Button with a label:
Button("Button label") {
    // Action to perform when button is tapped
}
  1. Button with a closure label:
Button {
    // Action to perform when button is tapped
} label: {
    // Something else as the label, e.g., an image
    Text("Button label")
}

The second way is commonly used when the button has a label other than plain text, such as an image.

Let’s use the first way to create a Button in a SwiftUI app:

struct ContentView: View {
    var body: some View {
        Button("Test") {
            // Action to perform when button is tapped
        }
        .font(.title)
    }
}

In the app, you will see a blue text that can be tapped to trigger the action.

To print something to the debugging console when the button is tapped, you can modify the code as follows:

struct ContentView: View {
    var body: some View {
        Button("Test") {
            print("test")
        }
        .font(.title)
    }
}

Please note that this will work only when you run the app, not in the Xcode preview.

Now let’s add another step to the app. We’ll print the value of a property inside the button label:

struct ContentView: View {
    @State var count = 0
    
    var body: some View {
        Button("Count: \(count)") {
        
        }
        .font(.title)
    }
}

To update the value of the count property when the button is tapped, we can modify the code as follows:

struct ContentView: View {
    @State var count = 0
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
        }
        .font(.title)
    }
}

However, you may encounter a compilation error: “Left side of mutating operator isn’t mutable: ‘self’ is immutable.” To fix this, you need to use the @State property wrapper before declaring the property:

struct ContentView: View {
    @State var count = 0
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
        }
        .font(.title)
    }
}

Now, when the label is clicked, the count property value will increment.

Please note that the counter will reset to 0 each time the app is run because we are not persisting the state. We’ll cover that later.

Tags: SwiftUI, Button view, app state, @State, property wrapper