0
votes

For UIKit on Mac Catalyst (and soon on iPadOS with trackpad support in iOS 13.4) we can use the UIHoverGestureRecognizer to listen for mouse hover event and adjust view accordingly. On AppKit on macOS there is the NSTrackingArea for tracking the mouse cursor.

I can't seem to find a way to recognize the hover gesture in SwiftUI. In the Gestures page of SwiftUI documentation there's only support for tap, long press, drag, magnification (zoom), and rotation. There is no indication of mouse hover.

Anyone have a way to do that?

The answer should preferably run natively on both iOS app (UIKit with UIHostingController) and macOS app (AppKit with NSHostingController)

1

1 Answers

1
votes

Apple just released the answer to this question alongside iOS 13.4!

Just use:

SomeView()
    .onHover { hover in
        print("Mouse hover: \(hover)")
        // Do something else
    }

Replace SomeView with your view, and that's it!

Note: Since this API came out from iOS 13.4, you cannot use this on apps that targets 13.0 (or you have cleverly use the if statement)

UPDATE: Looks like this had always worked on macOS (so don't have to specifically target 10.15.4, but I missed it :( )