SwiftUI Gesture Tutorial

Gestures can be added to any ordinary view in SwiftUI. In this tutorial a tap gesture is added to a text view to change the background color. 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 SwiftUIGestureTutorial 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 private var didTap: Bool = false
    
    var body: some View {
        // 2.
        Text("Tap me")
            .frame(minWidth:0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
            // 3.
            .gesture(TapGesture()
                .onEnded {
                    self.didTap.toggle()
                }
            )
            // 4.
            .background(didTap ? Color.blue : Color.red)
    }
}
  1. A State property is declared which will track if a tap gesture is detected.

  2. A text view is created which will span the entire window using the frame modifier

  3. a gesture modifier will toggle the boolean value of the state property

  4. The background color is changed according of the current state of the didTap property.

Go to the preview pane and click the live view button. Tap the text to change the background color.

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