App 6 — 24 Apps You Can Make Today

Move the Target

Drag a target around the screen with your finger using DragGesture.

  • ios
↓ Download Playgrounds File

Touch is what makes a phone a phone. This app teaches you how to track a finger as it moves across the screen — and move a view to follow it.

What you'll build

A target (a circle or bullseye) sitting in the middle of the screen. Drag it with your finger and it follows. Let go and it stays where you left it.

Key concepts

DragGesture — SwiftUI's gesture for tracking a finger's position and movement across the screen.

.gesture(
    DragGesture()
        .onChanged { value in
            offset = value.translation
        }
        .onEnded { value in
            position.x += value.translation.width
            position.y += value.translation.height
            offset = .zero
        }
)

@State for position — Track where the target is with a CGSize or CGPoint.

@State var position: CGSize = .zero
@State var offset: CGSize = .zero

.offset() — Move a view from its natural position by a given x/y amount. Combine state and offset to position your target.

Circle()
    .offset(x: position.width + offset.width,
            y: position.height + offset.height)

The two-phase drag

Notice the split between onChanged (live, while dragging) and onEnded (once, when the finger lifts). onChanged tracks the current gesture's translation; onEnded commits that translation into the stored position. That's the pattern for draggable views.

Download and run it

Open the Playgrounds file from GitHub, hit Run, and drag.

← All apps in this book