Library / Pickers, sliders & steppers

Canvas snap to alignment guide

Dragging an object in an editor until it snaps to a guide, grid line, or another object.

0ms 100ms 200ms 300ms 400ms
Feel
A single precise tick at the instant of alignment — the .alignment semantic haptic.
APIs
.sensoryFeedback(.alignment)
Minimum OS
iOS 17+
Raw .md
SwiftUI (iOS 17+)
import SwiftUI

struct SnappingCanvas: View {
    @State private var x: CGFloat = 60
    @State private var snapped = false
    let guideX: CGFloat = 180
    let snapRange: CGFloat = 12

    var body: some View {
        ZStack {
            // The guide line
            Rectangle().fill(.blue.opacity(snapped ? 1 : 0.25))
                .frame(width: 1).position(x: guideX, y: 150)

            RoundedRectangle(cornerRadius: 10)
                .fill(.orange)
                .frame(width: 70, height: 70)
                .position(x: x, y: 150)
                .gesture(
                    DragGesture()
                        .onChanged { value in
                            let raw = value.location.x
                            if abs(raw - guideX) < snapRange {
                                x = guideX
                                snapped = true   // triggers .alignment once
                            } else {
                                x = raw
                                snapped = false
                            }
                        }
                )
        }
        .frame(height: 300)
        .sensoryFeedback(.alignment, trigger: snapped) { _, new in new }
    }
}
Copied