Search code examples
swiftuilong-press

How to run function when long press gesture detected and stopped?


I want to implement following example: User needs to press a button at least 0.3 seconds long, after this the audio recording starts and after the user release the button the recording stops.

My solution is:

Image(systemName: "mic.circle")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 70)
            .foregroundColor(Color.blue)
            .onLongPressGesture(minimumDuration: 0.3){
                print("start recording...")
            }

How can I implement the function when the user stop pressing the button?


Solution

  • I could solve my problem, hope it's useful for some of you:

    @State private var isPressingDown: Bool = false
    
    Image(systemName: "mic.circle")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: 70)
            .foregroundColor(Color.blue)
            .onLongPressGesture(minimumDuration: 0.3){
                self.isPressingDown = true
                print("started")
            }
            .simultaneousGesture(
                DragGesture(minimumDistance: 0)
                    .onEnded{ _ in
                        if self.isPressingDown{
                            self.isPressingDown = false
                                print("ended")
                            }
                        }
                )