SwiftUI Gestures LongPressGesture

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

Demo.swift

ContentView.swift

App.swift

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() }
} }

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

Demo.swift

ContentView.swift

App.swift

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() }
  )
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *