问题
I’m trying to implement a long press button that changes the SF Symbol that I’m using only when I’m pressing down on the button. I’m not really sure where I should use the the Images as well. The problem is that when the I stop pressing, the button is triggered. Is there a way to don’t activate it (except while pressing down)?
What I’m looking for is a button that:
When pressed for 2 seconds, the Symbol changes, and after those 2 seconds, when released, the Symbol go back to the initial state.
struct heartButton: View {
@State private var isDetectingPress = false
var body: some View {
VStack {
Image(systemName: isDetectingPress ? "heart.fill" : "heart").font(.system(size: 16, weight: .regular))
Button(action: {
self.isDetectingPress.toggle()
}) {
Text("Button")
}
}
}
回答1:
Here is a solution. Tested with Xcode 11.5b.
struct heartButton: View {
@GestureState private var isDetectingPress = false
var body: some View {
VStack {
Image(systemName: isDetectingPress ? "heart.fill" : "heart").font(.system(size: 16, weight: .regular))
Text("Press")
.gesture(LongPressGesture(minimumDuration: 2).sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .local)).updating($isDetectingPress) { value, state, _ in
switch value {
case .second(true, nil):
state = true
default:
break
}
})
}
}
}
来源:https://stackoverflow.com/questions/61722327/swiftui-action-while-pressing-a-button