ViewOnTouch

检测 SwiftUI 视图上的触摸事件和坐标。灵感来自 https://www.hackingwithswift.com/quick-start/swiftui/how-to-detect-the-location-of-a-tap-inside-a-view

注意:处理位于滚动视图上的视图的触摸事件时要小心。在这种情况下,简单的点击只会触发 tapGesture 事件。

安装

Swift Package Manager (Swift 包管理器)

https://github.com/Jnis/ViewOnTouch.git

用法

MyView()
    .onTouch(type: longGestureAction == nil ? .allWithoutLongGesture : .all,
             perform: { location, event in
                print("\(location) - \(event.rawValue)")
                switch event {
                case .started:
                    viewModel.isTouchHandling = true
                    viewModel.touchDown?(location)
                case .moved:
                    viewModel.touchMove?(location)
                case .ended:
                    viewModel.isTouchHandling = false
                    viewModel.touchUp?(location)
                case .tapGesture where !viewModel.isTouchHandling:
                    viewModel.touchDown?(location)
                    viewModel.touchUp?(location)
                    tapAction?()
                case .longGestureStarted:
                    longGestureAction?(location, .started)
                case .longGestureMoved:
                    longGestureAction?(location, .moved)
                case .longGestureEnded:
                    longGestureAction?(location, .ended)
                default:
                    break
                }
            })

许可

MIT