user7842007
user7842007

Reputation:

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: {} )

Upvotes: 3

Views: 1854

Answers (2)

Vlad Grigorov
Vlad Grigorov

Reputation: 11378

I needed similar functionality but I could not achieve it with the pressing parameter. I solved it by sequencing 2 gesture recognizers:

struct MyView: View {
    @GestureState var isPressing = false

    Image("action-icon")
        .gesture(LongPressGesture(minimumDuration: 0.01)
            .sequenced(before: LongPressGesture(minimumDuration: .infinity))
            .updating($isPressing) { value, state, transaction in
                switch value {
                case .second(true, nil):
                    state = true
                    startVideoRecording()

                default: 
                    break
                }
            })
        .onChange(of: isPressing) { value in
            if value == false {
                stopVideoRecording()
            }
        }
}

Upvotes: 1

user7842007
user7842007

Reputation:

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: {})

Upvotes: 4

Related Questions