KMPopMenuButton.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // KMPopMenuButton.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2023/10/7.
  6. //
  7. import Cocoa
  8. class KMPopMenuButton: NSButton {
  9. override init(frame frameRect: NSRect) {
  10. super.init(frame: frameRect)
  11. self.setupButton()
  12. }
  13. required init?(coder: NSCoder) {
  14. super.init(coder: coder)
  15. self.setupButton()
  16. }
  17. private func setupButton() {
  18. self.addTrackingArea()
  19. self.wantsLayer = true
  20. self.layer?.backgroundColor = NSColor.clear.cgColor
  21. self.font = NSFont.systemFont(ofSize: 14)
  22. }
  23. func addTrackingArea() {
  24. let trackingArea = NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .inVisibleRect, .activeAlways, .mouseMoved], owner: self, userInfo: nil)
  25. self.addTrackingArea(trackingArea)
  26. }
  27. override func mouseEntered(with event: NSEvent) {
  28. super.mouseEntered(with: event)
  29. if self.isEnabled {
  30. if #available(macOS 10.14, *) {
  31. self.layer?.backgroundColor = NSColor.controlAccentColor.cgColor
  32. } else {
  33. self.layer?.backgroundColor = NSColor.blue.cgColor
  34. }
  35. self.setTitleColorWithColor(NSColor.white, font: nil)
  36. }
  37. }
  38. override func mouseExited(with event: NSEvent) {
  39. super.mouseExited(with: event)
  40. if self.isEnabled {
  41. self.layer?.backgroundColor = NSColor.clear.cgColor
  42. self.setTitleColorWithColor(NSColor.labelColor, font: nil)
  43. }
  44. }
  45. override var intrinsicContentSize: NSSize {
  46. var size = super.intrinsicContentSize
  47. size.width += 45
  48. return size
  49. }
  50. override var state: NSControl.StateValue {
  51. didSet {
  52. if state == .on {
  53. if #available(macOS 10.14, *) {
  54. self.layer?.backgroundColor = NSColor.controlAccentColor.cgColor
  55. } else {
  56. self.layer?.backgroundColor = NSColor.blue.cgColor
  57. }
  58. self.setTitleColorWithColor(NSColor.white, font: nil)
  59. } else {
  60. self.layer?.backgroundColor = NSColor.clear.cgColor
  61. self.setTitleColorWithColor(NSColor.labelColor, font: nil)
  62. }
  63. }
  64. }
  65. func setTitleColorWithColor(_ color: NSColor?, font: NSFont?) {
  66. // 设置按钮文本颜色和字体
  67. if let color = color {
  68. let titleAttributes: [NSAttributedString.Key: Any] = [
  69. .foregroundColor: color
  70. ]
  71. self.attributedTitle = NSAttributedString(string: self.title, attributes: titleAttributes)
  72. }
  73. if let font = font {
  74. self.font = font
  75. }
  76. }
  77. }