KMCoverButton.swift 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // KMCoverButton.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2023/10/7.
  6. //
  7. import Cocoa
  8. @objc enum KMCoverAction: Int {
  9. case enter = 0
  10. case move
  11. case exit
  12. }
  13. @objcMembers
  14. class KMCoverButton: NSButton {
  15. // var coverAction: ((KMCoverButton, KMCoverAction) -> Void)?
  16. var coverAction: ((_ button: KMCoverButton, _ actionType: KMCoverAction) -> Void)?
  17. private var area: NSTrackingArea?
  18. deinit {
  19. if let trackingArea = area {
  20. self.removeTrackingArea(trackingArea)
  21. }
  22. }
  23. override func updateTrackingAreas() {
  24. super.updateTrackingAreas()
  25. if let existingArea = self.area {
  26. self.removeTrackingArea(existingArea)
  27. self.area = nil
  28. }
  29. let opts: NSTrackingArea.Options = [.mouseEnteredAndExited, .mouseMoved, .activeAlways]
  30. self.area = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil)
  31. if let trackingArea = self.area {
  32. self.addTrackingArea(trackingArea)
  33. }
  34. }
  35. override func mouseEntered(with event: NSEvent) {
  36. if let coverAction = coverAction {
  37. coverAction(self, .enter)
  38. }
  39. }
  40. override func mouseExited(with event: NSEvent) {
  41. if let coverAction = coverAction {
  42. coverAction(self, .exit)
  43. }
  44. }
  45. override func mouseMoved(with event: NSEvent) {
  46. if let coverAction = coverAction {
  47. coverAction(self, .move)
  48. }
  49. }
  50. }