Last active
November 17, 2024 15:18
-
-
Save Amzd/cb8ba40625aeb6a015101d357acaad88 to your computer and use it in GitHub Desktop.
Set the cursor that is displayed when hovering a View. (macOS, SwiftUI)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
extension View { | |
/// https://stackoverflow.com/a/61985678/3393964 | |
public func cursor(_ cursor: NSCursor) -> some View { | |
self.onHover { inside in | |
if inside { | |
cursor.push() | |
} else { | |
NSCursor.pop() | |
} | |
} | |
} | |
} |
For me, the correct cursor shows briefly but then disappears.
A year later I'm back here with code that works:
extension View {
public func cursor(_ cursor: NSCursor) -> some View {
if #available(macOS 13.0, *) {
return self.onContinuousHover { phase in
switch phase {
case .active(let p):
cursor.push()
case .ended:
NSCursor.pop()
}
}
} else {
return self.onHover { inside in
if inside {
cursor.push()
} else {
NSCursor.pop()
}
}
}
}
}
Nice! Thank you for updating here as I will fix this in my projects too :D @lucasfeijo
Like its name says, onContinuousHover
calls its callback continuously, resulting in many cursor pushes and only a single pop
at the end. The result is that when the cursor leaves the view, the original cursor is not restored. So here's my modification:
extension View {
public func cursor(_ cursor: NSCursor) -> some View {
if #available(macOS 13.0, *) {
return self.onContinuousHover { phase in
switch phase {
case .active(_):
guard NSCursor.current != cursor else { return }
cursor.push()
case .ended:
NSCursor.pop()
}
}
} else {
return self.onHover { inside in
if inside {
cursor.push()
} else {
NSCursor.pop()
}
}
}
}
}
@humblehacker We'll get it right eventually, meanwhile @apple has been ignoring this bug...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Honestly can't believe Button doesn't do this by default.