swiftuigesture

OnLongPressGesture release action (SwiftUI)


I see there is a .onLongPressGesture(minimumDuration:maximumDistance:pressing:perform:).

However there isnt enough documentation for me to understand how to perform an action when the user releases the button.

A good example to understand what I am talking about is when you hold down a button to start recording a video and let go to stop the recording.

.onLongPressGesture(minimumDuration: 0.5, maximumDistance: 100, pressing: {}, perform: {} )

Solution

  • The answer to this is by calling the identifier like this.

    1. Created a state that tracks if the user has pressed the button
    @State var hasPressed = false
    
    1. On the pressing parameter, use the state to perform an action depending on if the user is pressing the button or not.
    .onLongPressGesture(minimumDuration: 0.5, maximumDistance: 100, pressing: {
                                pressing in
                                self.hasPressed = pressing
                                if pressing {action1}
                                if !pressing {action2}
                            }, perform: {})