Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active March 21, 2022 17:24
Show Gist options
  • Save mminer/663706a6e347b584d7d0203bd27f7fd3 to your computer and use it in GitHub Desktop.
Save mminer/663706a6e347b584d7d0203bd27f7fd3 to your computer and use it in GitHub Desktop.
NSView subclass that applies an effect when the mouse hovers over it.
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