Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 46 ยท Polish and Platform Features

Gestures, Shapes, Canvas and Charts

Learn SwiftUI gestures (tap, drag, long press, GestureState), custom Shape and Path drawing, Canvas for fast graphics, and Swift Charts basics with runnable stand-ins.

Buttons and lists cover most of an app, but the moments that make an app feel alive are often custom: dragging a card across the screen, pressing and holding to reveal a menu, a progress ring that fills smoothly, a chart of your week. SwiftUI covers all of these with the same declarative style you already know. Gestures are values you attach to views, shapes are structs that describe a path, Canvas draws thousands of elements quickly, and the Charts framework turns data into marks.

This lesson has four parts: gestures and how they combine, the Shape and Path types, Canvas for immediate-mode drawing, and the first steps with Swift Charts. Real SwiftUI code cannot run on this site, so it appears in read-only blocks. The two TryIts are honest stand-ins that run the underlying logic: how raw touches become a tap, long press or drag, and how data and geometry become coordinates. You should know modifiers and @State first, and animations pair naturally with everything below.

Four tools for custom interaction

Gestures Tap, drag, long press, pinch.
Shapes Paths you can fill and animate.
Canvas Fast drawing of many items.
Charts Data turned into marks.

Pick the simplest tool that does the job.

1 / 2

Gestures

The quickest gesture is the tap modifier:

Swift
Text("Like")
    .onTapGesture {
        likeCount += 1
    }

onTapGesture(count: 2) waits for a double tap. For anything that is really a button, use Button instead: it gets accessibility, highlight states and keyboard support for free, while a view with only onTapGesture is invisible to VoiceOver as an actionable control.

For richer input you create a gesture value and attach it with .gesture(_:). The main ones are:

  • TapGesture(count:): one or more taps.
  • LongPressGesture(minimumDuration:maximumDistance:): a press held long enough.
  • DragGesture(minimumDistance:coordinateSpace:): a finger moving across the screen.
  • MagnifyGesture and RotateGesture: pinch and two-finger rotation (iOS 17 and later; earlier systems call them MagnificationGesture and RotationGesture).

A drag reports a value with startLocation, location, translation (the distance from the start), velocity and predictedEndTranslation (where it would land if it kept coasting).

GestureState

While a drag is in progress you usually want a temporary offset that snaps back when the finger lifts. @GestureState does exactly that: it changes during the gesture and resets itself to its initial value when the gesture ends or is cancelled.

Swift
struct DraggableCard: View {
    @GestureState private var dragOffset = CGSize.zero
    @State private var restingOffset = CGSize.zero

    var body: some View {
        RoundedRectangle(cornerRadius: 16)
            .fill(.indigo)
            .frame(width: 120, height: 160)
            .offset(
                x: restingOffset.width + dragOffset.width,
                y: restingOffset.height + dragOffset.height
            )
            .gesture(
                DragGesture()
                    .updating($dragOffset) { value, state, _ in
                        state = value.translation
                    }
                    .onEnded { value in
                        restingOffset.width += value.translation.width
                        restingOffset.height += value.translation.height
                    }
            )
    }
}

The split is the key pattern. dragOffset (gesture state) holds the live finger movement and disappears afterwards; restingOffset (normal state) stores where the card stays. If you only wrote to @State in .onChanged, you would also need to handle cancellation yourself.

Combining gestures

Gestures can be composed:

  • a.sequenced(before: b): b only starts after a succeeds, for example long press, then drag to reorder.
  • a.simultaneously(with: b): both run at the same time, such as pinch and rotate together.
  • a.exclusively(before: b): a wins if it matches, otherwise b.

When a parent and a child both have gestures, the child normally wins. Use .highPriorityGesture(_:) to make a parent's gesture win, or .simultaneousGesture(_:) to let both recognize. A common bug is a drag on a ScrollView child that blocks scrolling; give the drag a minimumDistance or restrict it to a handle.

Gestures can also be made accessible. Add .accessibilityAction(named: "Delete") { ... } so VoiceOver users can trigger what swipes and long presses do for others.

The first TryIt is a stand-in for the recognizer. UIKit and SwiftUI decide between tap, long press and drag from raw touch events using thresholds. Here is a simplified version: a touch is a list of events with a time and position, and the classifier checks duration and distance. It also shows the GestureState behavior, where the live offset returns to zero after the finger lifts.

Swift From raw touches to tap, long press or drag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The card ends at x=100, the total drag, and live returns to 0 on its own. This is why the pattern needs both a transient value and a stored one.

Shapes and paths

A Shape is a struct with one required method that turns a rectangle into a Path:

Swift
struct Triangle: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.midX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
        path.closeSubpath()
        return path
    }
}

Triangle()
    .fill(.orange)
    .frame(width: 120, height: 100)

A Path is built with commands like move(to:), addLine(to:), addArc(center:radius:startAngle:endAngle:clockwise:), addQuadCurve and addCurve (Bezier curves), and closeSubpath(). The rectangle passed to path(in:) is the space the parent offered, so draw in relative coordinates (rect.midX, rect.width * 0.25) and the shape scales to any size. That follows the layout rules: a shape is flexible and takes whatever size it is proposed.

Shapes are views, so they take .fill(_:), .stroke(_:lineWidth:) and .stroke(style: StrokeStyle(lineWidth:lineCap:lineJoin:dash:)). The built-in shapes are Rectangle, RoundedRectangle, Circle, Ellipse and Capsule.

trim(from:to:) draws only part of a shape's outline. It is the classic way to build a progress ring:

Swift
Circle()
    .trim(from: 0, to: progress)
    .stroke(.green, style: StrokeStyle(lineWidth: 12, lineCap: .round))
    .rotationEffect(.degrees(-90))
    .animation(.smooth, value: progress)

trim is animatable, so changing progress sweeps the ring smoothly. For your own parameters, add animatableData as shown in the animations lesson.

Canvas

A shape is a view, so each one is tracked by SwiftUI. That is wonderful for ten shapes and wasteful for ten thousand. Canvas gives you a drawing context and a size, then you issue immediate drawing commands. SwiftUI does not keep a view for each item.

Swift
Canvas { context, size in
    for index in 0..<200 {
        let x = size.width * Double(index) / 200
        let y = size.height / 2 + sin(Double(index) / 8) * 40
        let dot = Path(ellipseIn: CGRect(x: x, y: y, width: 4, height: 4))
        context.fill(dot, with: .color(.blue))
    }

    context.draw(Text("Sine wave"), at: CGPoint(x: size.width / 2, y: 16))
}
.frame(height: 160)

Pair it with TimelineView(.animation) and the closure runs every frame, which makes particle effects and clocks simple. The trade-offs are real: items inside a canvas have no identity, no per-item animation by modifiers and no automatic accessibility. If the picture carries meaning, add .accessibilityLabel to the canvas or provide .accessibilityChildren { ... } with real views. Choose Canvas for many items or per-frame art; choose shapes when you need a handful of animated, accessible pieces.

Swift Charts

Swift Charts (the Charts framework, iOS 16 and later) maps data to marks. You declare which property goes on which axis, and the framework creates scales, axes and gridlines.

Swift
import Charts

struct DaySteps: Identifiable {
    let id = UUID()
    let day: String
    let steps: Int
}

struct StepsChart: View {
    let data: [DaySteps]

    var body: some View {
        Chart(data) { item in
            BarMark(
                x: .value("Day", item.day),
                y: .value("Steps", item.steps)
            )
            .foregroundStyle(item.steps >= 8000 ? .green : .gray)
        }
        .chartYScale(domain: 0...12000)
        .frame(height: 220)
    }
}

The marks you will meet first are BarMark, LineMark, PointMark, AreaMark, RuleMark (a reference line) and, from iOS 17, SectorMark for pie and donut charts. .value("Label", x) gives each axis a name that VoiceOver reads and that the chart uses for its default axis titles. Use .foregroundStyle(by: .value("Type", item.kind)) to split data into colored series with an automatic legend. Customize axes with chartXAxis, chartYAxis and chartYScale.

Charts are accessible by default because the marks carry values, which is a strong reason to prefer them over a hand-drawn Canvas for data. They are also a good fit for the habit tracker and expense tracker projects.

The second TryIt shows what happens under the chart: scales that map data values to coordinates, and a polygon built the way a custom Shape would build its Path. It prints a text bar chart and the corner points of a hexagon.

Swift Scales and path points behind drawing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The hexagon is computed from the rectangle it receives, so the small version starts at (20.0, 0.0) while the large one starts at (50.0, 0.0). That is exactly the habit to build in a Shape: never hard-code sizes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a @GestureState value when the gesture ends?

    GestureState is temporary: it resets to its initial value when the gesture ends or is cancelled, so you copy the result to @State in onEnded if you want to keep it.
  2. 2. Why prefer Button over a view with onTapGesture for a real action?

    A Button is exposed to assistive technologies as a control and has standard visual and keyboard behavior. A bare tap gesture has none of that.
  3. 3. What is the main reason to choose Canvas over many Shape views?

    Canvas uses immediate drawing commands, so thousands of items do not each create a view. The cost is no per-item identity or automatic accessibility.
  4. 4. In a Shape, why should path(in:) use values like rect.midX instead of fixed numbers?

    The rect is the space offered by the layout system. Relative coordinates make the same shape work at any size.

Summary

  • Attach gestures with .gesture(_:); onTapGesture is fine for quick taps, but real actions deserve a Button.
  • @GestureState holds live gesture values and resets itself; keep final results in @State.
  • Combine gestures with sequenced, simultaneously and exclusively, and adjust priority with highPriorityGesture or simultaneousGesture.
  • A Shape returns a Path for a given rect; use relative coordinates, fill, stroke and trim.
  • Canvas is for many items or per-frame drawing, at the cost of identity and automatic accessibility.
  • Swift Charts maps data to marks (BarMark, LineMark, PointMark, AreaMark, RuleMark, SectorMark) and gives you scales and axes.

Next: Accessibility and Localization.