我正在尝试制作一个控制计数器的按钮。如果您点击它,计数器将增加一。但是,如果您点击并按住它,我希望计数器在您按住它时每n秒上升一格,并继续这样做直到放开为止。
如果我使用以下代码:
@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秒钟后被调用。
我想要某种方式来保持调用代码,以在手指按下视图时不断更新计数器-不仅仅是在检测到长按之后一次。
答案 0 :(得分:1)
使用以下组合跟踪连续按下状态
通过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
}
}
}