NSButton+CustomAppearance.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // NSButton+CustomAppearance.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by kdanmobile on 2023/10/26.
  6. //
  7. import Foundation
  8. let NSButtonAddHoverKey = "NSButtonAddHoverKey"
  9. let NSButtonTrackingAreaKey = "NSButtonTrackingAreaKey"
  10. var placeholderImage: NSImage?
  11. extension NSButton{
  12. var addHoverEffect: Bool {
  13. get {
  14. return (objc_getAssociatedObject(self, NSButtonAddHoverKey) as? NSNumber)?.boolValue ?? false
  15. }
  16. set {
  17. removeTrackingArea(self.neededTrackingArea ?? NSTrackingArea())
  18. if newValue {
  19. addNewTrackingArea()
  20. }
  21. objc_setAssociatedObject(self, NSButtonAddHoverKey, NSNumber(value: newValue), .OBJC_ASSOCIATION_RETAIN)
  22. }
  23. }
  24. var neededTrackingArea: NSTrackingArea? {
  25. get {
  26. return objc_getAssociatedObject(self, NSButtonTrackingAreaKey) as? NSTrackingArea
  27. }
  28. set {
  29. objc_setAssociatedObject(self, NSButtonTrackingAreaKey, newValue, .OBJC_ASSOCIATION_RETAIN)
  30. }
  31. }
  32. func addNewTrackingArea() {
  33. self.wantsLayer = true
  34. let trackingArea = NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .inVisibleRect, .activeAlways], owner: self, userInfo: nil)
  35. self.addTrackingArea(trackingArea)
  36. self.neededTrackingArea = trackingArea
  37. }
  38. open override func mouseExited(with event: NSEvent) {
  39. super.mouseExited(with: event)
  40. if self.addHoverEffect {
  41. if !self.isEnabled {
  42. return
  43. }
  44. if (self.image != nil) && (self.alternateImage != nil) {
  45. self.alternateImage = self.image
  46. self.image = placeholderImage
  47. }
  48. }
  49. }
  50. open override func mouseEntered(with event: NSEvent) {
  51. super.mouseEntered(with: event)
  52. if self.addHoverEffect {
  53. if !self.isEnabled {
  54. return
  55. }
  56. if (self.image != nil) && (self.alternateImage != nil) {
  57. placeholderImage = self.image
  58. self.image = self.alternateImage
  59. }
  60. }
  61. }
  62. }