SwiftUI Gestures
SwiftUI Gestures
Handle taps, drags, and other interactions with .gesture and built-in gesture recognizers.
Tap and Long Press
Handle taps and long presses with .onTapGesture and .onLongPressGesture.
Syntax:
.onTapGesture { ... }.onLongPressGesture(minimumDuration:perform:)
Example
import SwiftUI
struct TapLongPressDemo: View {
@State private var on = false
@State private var pressed = false
var body: some View {
Circle()
.fill(on ? .green : .gray)
.frame(width: 80, height: 80)
.scaleEffect(pressed ? 0.9 : 1)
.onTapGesture { on.toggle() }
.onLongPressGesture(minimumDuration: 0.5) { pressed.toggle() }
}
}
import SwiftUI
struct ContentView: View {
var body: some View { TapLongPressDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example toggles color on tap and briefly scales the circle on a long-press.
DragGesture
Track finger movement by attaching a DragGesture to update an offset.
Syntax: .gesture(DragGesture().onChanged { value in ... }.onEnded { ... })
Example
import SwiftUI
struct DragDemo: View {
@State private var offset: CGSize = .zero
var body: some View {
Text("Drag me")
.padding(12)
.background(.blue.opacity(0.1))
.cornerRadius(8)
.offset(offset)
.gesture(
DragGesture()
.onChanged { value in offset = value.translation }
.onEnded { _ in withAnimation(.spring()) { offset = .zero } }
)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { DragDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example follows the finger while dragging and springs back to the origin on release.
Combining Gestures
Use .simultaneousGesture or .highPriorityGesture to coordinate multiple gestures.
Syntax:
.simultaneousGesture(TapGesture()).highPriorityGesture(DragGesture())
Example
import SwiftUI
struct CombineGesturesDemo: View {
@State private var tapped = 0
@State private var dragged = false
var body: some View {
Rectangle()
.fill(dragged ? .orange : .purple)
.frame(height: 120)
.overlay(Text("taps: \(tapped)"))
.simultaneousGesture(TapGesture().onEnded { tapped += 1 })
.highPriorityGesture(DragGesture().onChanged { _ in dragged = true }.onEnded { _ in dragged = false })
}
}
import SwiftUI
struct ContentView: View {
var body: some View { CombineGesturesDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example counts taps while also reacting to drags, demonstrating gesture composition.
Tip: Combine gestures with .simultaneousGesture or .highPriorityGesture to coordinate interactions.