How do you detect a SwiftUI touchDown event with no movement or duration?

后端 未结 6 830
无人及你
无人及你 2020-12-19 02:21

I\'m trying to detect when a finger first makes contact with a view in SwiftUI. I could do this very easily with UIKit Events but can\'t figure this out in SwiftUI.

I

6条回答
  •  醉酒成梦
    2020-12-19 02:56

    You can create a view modifier this way:

    extension View {
        func onTouchDownGesture(callback: @escaping () -> Void) -> some View {
            modifier(OnTouchDownGestureModifier(callback: callback))
        }
    }
    
    private struct OnTouchDownGestureModifier: ViewModifier {
        @State private var tapped = false
        let callback: () -> Void
    
        func body(content: Content) -> some View {
            content
                .simultaneousGesture(DragGesture(minimumDistance: 0)
                    .onChanged { _ in
                        if !self.tapped {
                            self.tapped = true
                            self.callback()
                        }
                    }
                    .onEnded { _ in
                        self.tapped = false
                    })
        }
    }
    

    Now you can use it like:

    struct MyView: View {
        var body: some View {
            Text("Hello World")
                .onTouchDownGesture {
                    print("View did tap!")
                }
        }
    }
    

提交回复
热议问题