Tracking Hover Location in SwiftUI
For a while we only had onHover(perform:) modifier in SwiftUI that is called when the user moves the pointer over or away from the view’s frame. There used to be no official way to continuously track the pointer location. This changed with the introduction of onContinuousHover(coordinateSpace:perform:) in macOS 13 and iPadOS 16.
The new modifier lets us read the current HoverPhase and reports the exact location of the pointer when it’s within the view’s bounds. Let’s see it in action.
Update (2023-02-13): John Siracusa (Mastodon):
SwiftUI’s
.onHover
View method fails sporadically when applied to a view that does not cover the entire containing window and that window has a “clear” background color. This sample project demonstrates the bug, which has been filed with Apple as FB11988707.The workaround is to make the background color anything that is not “clear.”
Update (2023-03-08): Donny Wals:
Long shot: in a macOS app that leverages this gist for a more reliable hover effect in SwiftUI[…]
On some macs with macOS 12.x this is completely fine. On others with 12.x the app is fine until the very first time the app is clicked. After that happens there’s a huge slowdown that seems related to the code in that gist (based on Instruments trace) but without a reliable reproduction on virtually identical machines I have no idea where to start debugging.