SwiftUI Button Tutorial

In SwiftUI a button is a control that performs a action when triggered. In this tutorial a button can be clicked to increment a value. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIButtonTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @State var counter = 0
    var body: some View {
        
        VStack {
            // 2.
            Button(action:
                { self.counter += 1
            }) {
                HStack {
                    Image(systemName: "plus.circle")
                    Text("Add 1")
                }
            }
            .padding()
            .background(Color.blue)
            
            // 3.
            Text("\(counter)")
            .padding()
        }
        .foregroundColor(Color.black)
        .font(.title)
    }
}
  1. A state property is declared to hold the current counter value

  2. A button is displayed containing an Image and a Text view. When clicked the counter property is incremented.

  3. The current counter value is displayed inside the Text view

Go to the Preview pane. Select the Live view button. Click the button to update the Text view.

The source code of the SwiftUIButtonTutorial can be downloaded at the ioscreator repository on Github.