123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import Cocoa
- class KMPopMenuButton: NSButton {
- override init(frame frameRect: NSRect) {
- super.init(frame: frameRect)
- self.setupButton()
- }
-
- required init?(coder: NSCoder) {
- super.init(coder: coder)
- self.setupButton()
- }
-
- private func setupButton() {
- self.addTrackingArea()
- self.wantsLayer = true
- self.layer?.backgroundColor = NSColor.clear.cgColor
- self.font = NSFont.systemFont(ofSize: 14)
- }
-
- func addTrackingArea() {
- let trackingArea = NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .inVisibleRect, .activeAlways, .mouseMoved], owner: self, userInfo: nil)
- self.addTrackingArea(trackingArea)
- }
-
- override func mouseEntered(with event: NSEvent) {
- super.mouseEntered(with: event)
-
- if self.isEnabled {
- if #available(macOS 10.14, *) {
- self.layer?.backgroundColor = NSColor.controlAccentColor.cgColor
- } else {
- self.layer?.backgroundColor = NSColor.blue.cgColor
- }
- self.setTitleColorWithColor(NSColor.white, font: nil)
- }
- }
-
- override func mouseExited(with event: NSEvent) {
- super.mouseExited(with: event)
-
- if self.isEnabled {
- self.layer?.backgroundColor = NSColor.clear.cgColor
- self.setTitleColorWithColor(NSColor.labelColor, font: nil)
- }
- }
-
- override var intrinsicContentSize: NSSize {
- var size = super.intrinsicContentSize
- size.width += 45
- return size
- }
-
- override var state: NSControl.StateValue {
- didSet {
- if state == .on {
- if #available(macOS 10.14, *) {
- self.layer?.backgroundColor = NSColor.controlAccentColor.cgColor
- } else {
- self.layer?.backgroundColor = NSColor.blue.cgColor
- }
- self.setTitleColorWithColor(NSColor.white, font: nil)
- } else {
- self.layer?.backgroundColor = NSColor.clear.cgColor
- self.setTitleColorWithColor(NSColor.labelColor, font: nil)
- }
- }
- }
-
-
- func setTitleColorWithColor(_ color: NSColor?, font: NSFont?) {
-
- if let color = color {
- let titleAttributes: [NSAttributedString.Key: Any] = [
- .foregroundColor: color
- ]
- self.attributedTitle = NSAttributedString(string: self.title, attributes: titleAttributes)
- }
- if let font = font {
- self.font = font
- }
- }
-
- }
|