KMHoverView.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // KMHoverView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/6/7.
  6. //
  7. import Cocoa
  8. enum KMHoverAction: Int {
  9. case enter = 1
  10. case move = 2
  11. case exit = 3
  12. }
  13. // hover 基类
  14. class KMHoverView: NSView {
  15. private var _area: NSTrackingArea?
  16. var hoverAction: ((KMHoverView, KMHoverAction)->Void)?
  17. deinit {
  18. if let area_ = self._area {
  19. self.removeTrackingArea(area_)
  20. }
  21. }
  22. override func updateTrackingAreas() {
  23. super.updateTrackingAreas()
  24. if let area_ = self._area {
  25. self.removeTrackingArea(area_)
  26. self._area = nil
  27. }
  28. self._area = NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways], owner: self)
  29. if let area_ = self._area {
  30. self.addTrackingArea(area_)
  31. }
  32. }
  33. override func mouseEntered(with event: NSEvent) {
  34. guard let callback = self.hoverAction else {
  35. return
  36. }
  37. callback(self, .enter)
  38. }
  39. override func mouseExited(with event: NSEvent) {
  40. guard let callback = self.hoverAction else {
  41. return
  42. }
  43. callback(self, .exit)
  44. }
  45. override func mouseMoved(with event: NSEvent) {
  46. guard let callback = self.hoverAction else {
  47. return
  48. }
  49. callback(self, .move)
  50. }
  51. }