Skip to content

Instantly share code, notes, and snippets.

@OskarGroth
Created March 17, 2019 11:52
Show Gist options
  • Save OskarGroth/97ec53fa8227909bedb0be5cb2244c72 to your computer and use it in GitHub Desktop.
Save OskarGroth/97ec53fa8227909bedb0be5cb2244c72 to your computer and use it in GitHub Desktop.
public class MouseTrackingView: NSView {
public var callback: ((Bool) -> Void)?
private var trackingArea: NSTrackingArea?
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
commonInit()
}
fileprivate func commonInit() {
updateTrackingAreas()
}
override public func updateTrackingAreas() {
super.updateTrackingAreas()
if let trackingArea = trackingArea {
removeTrackingArea(trackingArea)
}
trackingArea = NSTrackingArea(rect: bounds, options: [.activeInKeyWindow, .mouseEnteredAndExited], owner: self, userInfo: nil)
addTrackingArea(trackingArea!)
}
override public func mouseEntered(with event: NSEvent) {
super.mouseEntered(with: event)
callback?(true)
}
override public func mouseExited(with event: NSEvent) {
super.mouseExited(with: event)
callback?(false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment