KMCoverButton.swift 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // KMCoverButton.swift
  3. // PDF Reader Pro
  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: ((_ button: KMCoverButton, _ actionType: KMCoverAction) -> Void)?
  16. private var area: NSTrackingArea?
  17. deinit {
  18. if let trackingArea = area {
  19. self.removeTrackingArea(trackingArea)
  20. }
  21. }
  22. override func updateTrackingAreas() {
  23. super.updateTrackingAreas()
  24. if let existingArea = self.area {
  25. self.removeTrackingArea(existingArea)
  26. self.area = nil
  27. }
  28. let opts: NSTrackingArea.Options = [.mouseEnteredAndExited, .mouseMoved, .activeAlways]
  29. self.area = NSTrackingArea(rect: bounds, options: opts, owner: self, userInfo: nil)
  30. if let trackingArea = self.area {
  31. self.addTrackingArea(trackingArea)
  32. }
  33. }
  34. override func mouseEntered(with event: NSEvent) {
  35. if let coverAction = coverAction {
  36. coverAction(self, .enter)
  37. }
  38. }
  39. override func mouseExited(with event: NSEvent) {
  40. if let coverAction = coverAction {
  41. coverAction(self, .exit)
  42. }
  43. }
  44. override func mouseMoved(with event: NSEvent) {
  45. if let coverAction = coverAction {
  46. coverAction(self, .move)
  47. }
  48. }
  49. }