Skip to content

Instantly share code, notes, and snippets.

@xocialize
Forked from mminer/HoverView.swift
Created April 9, 2025 23:26
Show Gist options
  • Select an option

  • Save xocialize/e908a55db8c5a273147f8ab0128b331b to your computer and use it in GitHub Desktop.

Select an option

Save xocialize/e908a55db8c5a273147f8ab0128b331b 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