SwiftUI Gestures LongPressGesture
SwiftUI Gestures: LongPressGesture
Detect a sustained press using LongPressGesture to trigger state changes.
Syntax
Long press handler: .onLongPressGesture(minimumDuration: 0.5) { ... } or LongPressGesture(minimumDuration:) with .onEnded.
Toggle on Long Press
Hold for 0.5 seconds to toggle the label between "Hold me" and "Pressed".
Example
import SwiftUI
struct LongPressDemo: View {
@State private var pressed = false
var body: some View {
Text(pressed ? "Pressed" : "Hold me")
.padding(12)
.background(.blue.opacity(0.1))
.cornerRadius(8)
.onLongPressGesture(minimumDuration: 0.5) { pressed.toggle() }
}
}
import SwiftUI
struct ContentView: View {
var body: some View { LongPressDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the label toggles between "Hold me" and "Pressed" when held for 0.5 seconds.
Show Progress During Long Press
Track the in-progress state and scale the view while pressing using LongPressGesture with .updating.
Example
import SwiftUI
struct LongPressProgressDemo: View {
@GestureState private var isPressing = false
@State private var done = false
var body: some View {
Circle()
.fill(done ? .green : .gray)
.frame(width: 80, height: 80)
.scaleEffect(isPressing ? 0.9 : 1)
.gesture(
LongPressGesture(minimumDuration: 0.6)
.updating($isPressing) { value, state, _ in state = value }
.onEnded { _ in done.toggle() }
)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { LongPressProgressDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the circle scales while pressed and toggles color on release.