KMCustomButton.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // KMCustomButton.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/18.
  6. //
  7. import Cocoa
  8. @objcMembers class KMCustomButton: NSButton {
  9. @objc var mouseMoveCallback: ((_ mouseEntered: Bool)->Void)?
  10. override func draw(_ dirtyRect: NSRect) {
  11. super.draw(dirtyRect)
  12. if self.isHighlighted {
  13. let radius = self.layer?.cornerRadius ?? 0
  14. let context = NSGraphicsContext.current
  15. context?.saveGraphicsState()
  16. NSBezierPath(roundedRect: dirtyRect, xRadius: radius, yRadius: radius).setClip()
  17. NSColor(deviceRed: 0, green: 0, blue: 0, alpha: 0.15).set()
  18. dirtyRect.fill(using: .sourceOver)
  19. context?.restoreGraphicsState()
  20. }
  21. }
  22. override func viewDidMoveToWindow() {
  23. super.viewDidMoveToWindow()
  24. if self.window != nil {
  25. self.addTrackingRect(self.bounds, owner: self, userData: nil, assumeInside: false)
  26. }
  27. }
  28. override func setFrameSize(_ newSize: NSSize) {
  29. super.setFrameSize(newSize)
  30. self.addTrackingRect(NSMakeRect(0, 0, newSize.width, newSize.height), owner: self, userData: nil, assumeInside: false)
  31. }
  32. override func mouseEntered(with event: NSEvent) {
  33. guard let callback = self.mouseMoveCallback else {
  34. return
  35. }
  36. callback(true)
  37. }
  38. override func mouseExited(with event: NSEvent) {
  39. guard let callback = self.mouseMoveCallback else {
  40. return
  41. }
  42. callback(false)
  43. }
  44. }