-
-
Save xocialize/e908a55db8c5a273147f8ab0128b331b to your computer and use it in GitHub Desktop.
NSView subclass that applies an effect when the mouse hovers over it.
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 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