SwiftUI Drag Gesture Tutorial

In SwiftUI gestures can be added to a view..In this tutorial a drag gesture is added to a circle so that it can be moved around the screen . SwiftUI requires Xcode 11 and MacOS Catalina, which 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 SwiftUIDragGestureTutorial 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 currentPosition: CGSize = .zero
    @State private var newPosition: CGSize = .zero
    
    var body: some View {
        // 2.
        Circle()
            .frame(width: 100, height: 100)
            .foregroundColor(Color.red)
            .offset(x: self.currentPosition.width, y: self.currentPosition.height)
            // 3.
            .gesture(DragGesture()
                .onChanged { value in
                    self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
            }   // 4.
                .onEnded { value in
                    self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
                    print(self.newPosition.width)
                    self.newPosition = self.currentPosition
                }
        )
    }
}
  1. Two state properties are created to keep track of the position during and at the end of the drag gesture.

  2. A circle is displayed. The position of the circle is equal to the position of the end of the gesture. At the start the position will be zero.

  3. a Drag Gesture is created, which will update the current position during the drag

  4. At the end of the drag gesture the new position is set.

Go to the Preview window and click the Live preview button. Drag the circle around the screen,.

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