.onLongPressGesture
May 27, 2024
LongPressGesture | Apple Developer Documentation
A gesture that succeeds when the user performs a long press.
https://developer.apple.com/documentation/swiftui/longpressgesture
Handling long-press gestures | Apple Developer Documentation
Detect extended duration taps on the screen, and use them to reveal contextually relevant content.
https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/handling_uikit_gestures/handling_long-press_gestures
1. Base structure
- onLongPressGesture: This is the core interaction:
minimumDuration: 3.0means the press needs to last at least 3 seconds.maximumDistance: 50means the finger can't move more than 50 points during the press.- Two blocks of code:
- Start of Press: The
isPressingblock triggers when the gesture starts and meets the minimum duration: - The
isCompletevariable is toggled (flipped between true and false) using an animation to make the rectangle grow smoothly. - End of Press: The second block triggers when the gesture ends. If the action hasn't succeeded (
!isSuccess) it resets theisCompletevariable after a slight delay (DispatchQueue.main.asyncAfter). - Gesture Completion (perform:): If the gesture meets all requirements, this block runs and sets
isSuccessto true,also with an animation.