How to detect the user hovering over a view
How to detect the user hovering over a view 관련
Updated for Xcode 15
In SwiftUI, any macOS app or any iPadOS app where a mouse is connected can detect when the user is hovering their pointer over a view, and respond to it appropriately.
There are two modifiers you'll want to use: onHover()
, and hoverEffect()
. The first of these allows you to track whether the pointer is currently hovering over the view, and is passed a Boolean reflecting that state. For example, this will color some text red or green depending on whether the pointer is hovering over it or not:
struct ContentView: View {
@State private var overText = false
var body: some View {
Text("Hello, World!")
.foregroundStyle(overText ? .green : .red)
.onHover { over in
overText = over
}
}
}
The hoverEffect()
modifier allows you to choose one of three ways the system can highlight the view when a hover happens: .highlight
transforms the pointer into the shape of the view while creating a gentle directional effect, .lift
transforms the pointer into the shape of the view while scaling up the view and placing a soft shadow behind it, and .automatic
selects whichever highlight effect it thinks is most appropriate.
Note that .automatic
is the default if you just apply the hoverEffect()
modifier without any parameters, but it isn't just selecting between .highlight
and .lift
– it's quite a different effect, and won't transform the pointer to match the shape of your view.
To try it out, here's some code that places a tappable text label on the screen, giving it a .lift
hover effect to make it clear that it's tappable:
struct ContentView: View {
var body: some View {
Text("Tap me!")
.font(.largeTitle)
.hoverEffect(.lift)
.onTapGesture {
print("Text tapped")
}
}
}
Tips
To try this out on the iPadOS simulator, go to the I/O menu and choose [Input]
> [Send Cursor to Device]
.