'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.
Solution 1:[1]
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.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Subha_26 |
Solution 2 | Alexander Sandberg |