我如何做出一个SwiftUI手势来在按下视图时保持运行代码 [英] How do I make a SwiftUI gesture that keeps running code while the view is pressed
问题描述
我正在尝试制作一个控制计数器的按钮.如果您点击它,则计数器将增加一.但是,如果您点击并按住它,我希望计数器在您按住它时每n秒上升一格,并继续这样做直到放开为止.
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.
如果我使用以下代码:
@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)")
}
}
然后,一秒钟后 isDetectingLongPress
变为true,然后立即变为false.并且 onEnded
中的打印也会在1秒钟后被调用.
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.
推荐答案
使用以下组合跟踪连续按下状态
Use instead the following combination to track continuous pressing down
通过Xcode 11.4/iOS 13.4测试
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
}
}
}
这篇关于我如何做出一个SwiftUI手势来在按下视图时保持运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!