How do I make a SwiftUI gesture that keeps running code while the view is pressed

北战南征 提交于 2021-01-27 21:54:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!