问题
I am trying to make a button that controls a counter. If you tap it, the counter goes up by one. But if you tap and hold it, I want the counter to go up by one every n seconds while you are holding it and keep doing that until you let go.
If I use code like:
@GestureState var isDetectingLongPress = false
var plusLongPress: some Gesture {
LongPressGesture(minimumDuration: 1)
.updating($isDetectingLongPress) { currentstate, gestureState, _ in
gestureState = currentstate
}
.onEnded { finished in
print("LP: finished \(finished)")
}
}
Then isDetectingLongPress becomes true after one second and then immediately becomes false. And the print in onEnded is called after 1 second as well.
I want some way to keep calling code to continuously update a counter while the finger is pressing the view -- not just once after a long press is detected.
回答1:
Use instead the following combination to track continuous pressing down
Tested with Xcode 11.4 / iOS 13.4
@GestureState var isLongPress = false // will be true till tap hold
var plusLongPress: some Gesture {
LongPressGesture(minimumDuration: 1).sequenced(before:
DragGesture(minimumDistance: 0, coordinateSpace:
.local)).updating($isLongPress) { value, state, transaction in
switch value {
case .second(true, nil):
state = true
// side effect here if needed
default:
break
}
}
}
来源:https://stackoverflow.com/questions/61523374/how-do-i-make-a-swiftui-gesture-that-keeps-running-code-while-the-view-is-presse