Gestures: Tap, Drag, Long Press and Magnify
Tap and Long Press
swift
Text("Tap me")
.onTapGesture { print("Tapped") }
.onTapGesture(count: 2) { print("Double tapped") }
.onLongPressGesture(minimumDuration: 0.6) { print("Long pressed") }
Accessibility: For real actions prefer
Button. A Button works with VoiceOver and keyboards automatically. A gesture on plain text does not.
Drag
swift
struct DraggableCircle: View {
@State private var offset: CGSize = .zero
@GestureState private var isDragging = false
var body: some View {
Circle()
.fill(isDragging ? .orange : .blue)
.frame(width: 100, height: 100)
.offset(offset)
.gesture(
DragGesture()
.updating($isDragging) { _, state, _ in state = true }
.onChanged { value in offset = value.translation }
.onEnded { _ in
withAnimation(.spring) { offset = .zero } // snap back
}
)
}
}
| Property | Use |
|---|---|
@GestureState | Temporary value that resets by itself when the gesture ends |
value.translation | How far the finger moved |
value.location | Current finger position |
value.predictedEndTranslation | Where it would end with momentum |
Magnify and Rotate
swift
struct PhotoZoom: View {
@State private var scale = 1.0
@State private var angle = Angle.zero
var body: some View {
Image(systemName: "photo")
.resizable().scaledToFit()
.frame(width: 200)
.scaleEffect(scale)
.rotationEffect(angle)
.gesture(
MagnifyGesture()
.onChanged { scale = $0.magnification }
.onEnded { _ in withAnimation { scale = 1 } }
)
.simultaneousGesture(
RotateGesture()
.onChanged { angle = $0.rotation }
)
}
}
Swipe-to-dismiss Card
swift
struct SwipeCard: View {
@State private var x: CGFloat = 0
var body: some View {
RoundedRectangle(cornerRadius: 20)
.fill(.pink.gradient)
.frame(width: 260, height: 340)
.rotationEffect(.degrees(Double(x) / 15))
.offset(x: x)
.gesture(
DragGesture()
.onChanged { x = $0.translation.width }
.onEnded { value in
if abs(value.translation.width) > 120 {
withAnimation { x = value.translation.width > 0 ? 600 : -600 }
} else {
withAnimation(.spring) { x = 0 }
}
}
)
}
}
Priority: If a parent and child both have gestures, use
.highPriorityGesture or .simultaneousGesture to decide who wins.
Conclusion
SwiftUI gestures are modifiers. Combine them with state to create draggable, zoomable and swipeable interfaces.
Quick Summary: Use onTapGesture, DragGesture, MagnifyGesture and RotateGesture with state, and @GestureState for temporary values.

