Michel
Michel

Reputation: 11753

Button with double action (tap & long press) in SwiftUI

Is it possible in SwiftUI to set a button with an action on tap and a different action on long press ?

I have tried this:

Button(action: {
    self.handleButtonTap()
})
{
    Text("My nice button")
        .foregroundColor(.primary)
}
.onLongPressGesture {
    print("Long pressed!")
}

or instead of:

.onLongPressGesture {
    print("Long pressed!")
}

using this:

.gesture(longPress)

where long press is something like:

var longPress: some Gesture {
  ....
}

But nothing seems to work. At best I have been able to attach the long press gesture to the Text of the button, but even in that case the normal tap cease to work.

Any good advice will be highly appreciated.

Upvotes: 7

Views: 3455

Answers (2)

Alexander Sandberg
Alexander Sandberg

Reputation: 1873

Here is another solution that doesn't trigger the regular tap action after every long press.

Button("Button") {
    // No tap action here
}
.simultaneousGesture(LongPressGesture().onEnded { _ in
    print("Long-pressed")
})
.simultaneousGesture(TapGesture().onEnded {
    print("Tapped")
})

I learned about this in this blog post: Supporting Both Tap and Long Press on a Button in SwiftUI

Note: This might not work as expected with Catalyst, which you can learn more about in the blog post above.

Upvotes: 11

Subha_26
Subha_26

Reputation: 450

Please check if this works for you:

Button("Button") {
    print("tapped")
}
.simultaneousGesture(LongPressGesture().onEnded { _ in
    print("long pressed")
})

Please note that tap action is executed after every long press in the above code. You can handle this with a simple Bool.

Upvotes: 2

Related Questions