swiftmacosswiftui

SwiftUI: Two-finger swipe ( scroll ) gesture


I'm interested in 2-finger swipe ( scroll ) gesture.

Not two-finger drag, but 2-finger swipe (without press). Like used in Safari to scroll up and down.

As I see noone of basic gestures will work for this: TapGesture - is not; LongPressGesture - not; DragGesture - not; MagnificationGesture - not; RotationGesture - not;

Have anyone some ideas how to do this?

I need at least direction to look at.



Solution

  • import Combine
    
    @main
    struct MyApp: App {
        @State var subs = Set<AnyCancellable>() // Cancel onDisappear
    
        @SceneBuilder
        var body: some Scene {
            WindowGroup {
                SomeWindowView()
                    /////////////
                    // HERE!!!!!
                    /////////////
                    .onAppear { trackScrollWheel() }
            }
        }
    }
    
    /////////////
    // HERE!!!!!
    /////////////
    extension MyApp {
        func trackScrollWheel() {
            NSApp.publisher(for: \.currentEvent)
                .filter { event in event?.type == .scrollWheel }
                .throttle(for: .milliseconds(200),
                          scheduler: DispatchQueue.main,
                          latest: true)
                .sink {
                    if let event = $0 {
                        if event.deltaX > 0 { print("right") }
                        if event.deltaX < 0 { print("left") }
                        if event.deltaY > 0 { print("down") }
                        if event.deltaY < 0 { print("up") }
                    }
                }
                .store(in: &subs)
        }
    }