Last active
March 21, 2022 17:24
-
-
Save mminer/663706a6e347b584d7d0203bd27f7fd3 to your computer and use it in GitHub Desktop.
NSView subclass that applies an effect when the mouse hovers over it.
This file contains 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 AppKit | |
class HoverView: NSView { | |
override var wantsUpdateLayer: Bool { | |
return true | |
} | |
private var isMouseOver = false { | |
didSet { | |
needsDisplay = true | |
} | |
} | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
wantsLayer = true | |
layerContentsRedrawPolicy = .onSetNeedsDisplay | |
let trackingArea = NSTrackingArea( | |
rect: bounds, | |
options: [.activeInKeyWindow, .mouseEnteredAndExited], | |
owner: self, | |
userInfo: nil | |
) | |
addTrackingArea(trackingArea) | |
} | |
override func updateLayer() { | |
super.updateLayer() | |
if isMouseOver { | |
// Apply hover style. | |
} else { | |
// Apply normal style. | |
} | |
} | |
override func mouseEntered(with event: NSEvent) { | |
super.mouseEntered(with: event) | |
isMouseOver = true | |
} | |
override func mouseExited(with event: NSEvent) { | |
super.mouseExited(with: event) | |
isMouseOver = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment