Home > Mobile >  SwiftUI: How can I deselect a button programmatically after the user completes a long press?
SwiftUI: How can I deselect a button programmatically after the user completes a long press?

Time:05-20

I have a button that can be long pressed for a different action. Here's the problem: if I release after the long press, while still hovering the button, the tap action still fires off. Is there a way I can automatically untap/deselect the button after my long press action runs? Thanks.

Button("Long Press Test") {
            print("Button Tapped")
        }
        .simultaneousGesture(LongPressGesture().onEnded { _ in
            print("Long Press Successful")
        })

CodePudding user response:

You just need to make the button action block empty. Now you will only get the long press action.

Button(action: {})
{
    Text("Long Press Test")
}
.simultaneousGesture(
    LongPressGesture()
        .onEnded { _ in
            print("Long Press Successful")
        }
)

CodePudding user response:

Your tap action just needs to be conditional. The LongPressGesture will always fire first as it reacts to the press. Tap reacts to the left, so that comes after the press. In LongPressGesture, you set a flag that causes the action to skip in Tap, and then you reset the flag in tap, after the conditional. An example:

struct ButtonTapOrPress: View {
    
    @State var longpPress = false
    
    var body: some View {
        Button("Long Press Test") {
            if !longpPress {
                    print("Button Tapped")
            }
            longpPress = false
                }
                .simultaneousGesture(LongPressGesture().onEnded { _ in
                    print("Long Press Successful")
                    longpPress = true
                })
    }
}
  • Related