SwiftUI 识别鼠标悬停 [英] SwiftUI Recognize mouse hover
问题描述
对于 Mac Catalyst 上的 UIKit(很快在 iOS 13.4 中支持触控板的 iPadOS 上),我们可以使用 UIHoverGestureRecognizer
来监听鼠标悬停事件并相应地调整视图.在 macOS 上的 AppKit 上,有用于跟踪鼠标光标的 NSTrackingArea
.
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.
我似乎找不到在 SwiftUI 中识别悬停手势的方法.在 SwiftUI 文档的 Gestures 页面中,仅支持点击、长按、拖动、放大(缩放)和旋转.没有鼠标悬停的迹象.
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?
答案最好在 iOS 应用(带有 UIHostingController
的 UIKit)和 macOS 应用(带有 NSHostingController
的 AppKit)上本地运行
The answer should preferably run natively on both iOS app (UIKit with UIHostingController
) and macOS app (AppKit with NSHostingController
)
推荐答案
Apple 刚刚与 iOS 13.4 一起发布了这个问题的答案!
Apple just released the answer to this question alongside iOS 13.4!
只需使用:
SomeView()
.onHover { hover in
print("Mouse hover: \(hover)")
// Do something else
}
用你的视图替换 SomeView
,就是这样!
Replace SomeView
with your view, and that's it!
注意:由于此 API 来自 iOS 13.4,因此您不能在面向 13.0 的应用程序上使用它(或者您巧妙地使用了 if
语句)
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)
更新: 看起来这在 macOS 上一直有效(所以不必专门针对 10.15.4,但我错过了 :( )
UPDATE: Looks like this had always worked on macOS (so don't have to specifically target 10.15.4, but I missed it :( )
这篇关于SwiftUI 识别鼠标悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!