'SwiftUI - how to detect long press on Button?
I have a Button where when it gets pressed, it performs some actions. But I would like to modify the same Button to detect a longer press, and perform a different set of processes. How do I modify this code to detect a long press?
Button(action: {
// some processes
}) {
Image(systemName: "circle")
.font(.headline)
.opacity(0.4)
}
Solution 1:[1]
Here is possible variant (tested with Xcode 11.2 / iSO 13.2).
Button("Demo") {
print("> tap")
}
.simultaneousGesture(LongPressGesture().onEnded { _ in
print(">> long press")
})
Solution 2:[2]
Daniel Wood's comment is correct in both statements. First, it is the cleanest solution. For the second, there is a straightforward workaround.
struct ContentView: View {
@State private var didLongPress = false
var body: some View {
Button("Demo") {
if self.didLongPress {
self.didLongPress = false
doLongPressThing()
} else {
doTapThing()
}
}.simultaneousGesture(
LongPressGesture().onEnded { _ in self.didLongPress = true }
)
}
}
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 | |
Solution 2 | TheLivingForce |