KMTextfieldButton.swift 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. //
  2. // KMTextfieldButton.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/2/15.
  6. //
  7. import Cocoa
  8. typealias MouseDownAction = (_ button: NSButton, _ itemString: String) -> ()
  9. class KMTextfieldButton: BaseXibView {
  10. @IBOutlet weak var titleLabel: NSTextField!
  11. @IBOutlet weak var imageView: NSImageView!
  12. @IBOutlet weak var button: NSButton!
  13. var createFilePopover: NSPopover?
  14. var data: [String] = []
  15. var mouseDownAction: MouseDownAction?
  16. var popWidth: CGFloat?
  17. var stringValue: String = "" {
  18. didSet {
  19. self.titleLabel.stringValue = stringValue
  20. }
  21. }
  22. var imageName: String = "" {
  23. didSet {
  24. self.imageView.image = NSImage(named: imageName)
  25. }
  26. }
  27. var isEnabled: Bool = true {
  28. didSet {
  29. self.titleLabel.isEnabled = isEnabled
  30. self.titleLabel.alphaValue = isEnabled ? 1 : 0.5
  31. self.imageView.isEnabled = isEnabled
  32. self.imageView.alphaValue = isEnabled ? 1 : 0.5
  33. self.button.isEnabled = isEnabled
  34. self.button.alphaValue = isEnabled ? 1 : 0.5
  35. }
  36. }
  37. var font: NSFont? {
  38. didSet {
  39. self.titleLabel.font = font
  40. }
  41. }
  42. var textColor: NSColor? {
  43. didSet {
  44. self.titleLabel.textColor = textColor
  45. }
  46. }
  47. override func draw(_ dirtyRect: NSRect) {
  48. super.draw(dirtyRect)
  49. // Drawing code here.
  50. }
  51. @IBAction func buttonAction(_ sender: NSButton) {
  52. if self.data.count != 0 {
  53. var popViewDataArr: [String] = []
  54. for string in self.data {
  55. popViewDataArr.append(NSLocalizedString(string, comment: ""))
  56. }
  57. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  58. let createFilePopover: NSPopover = NSPopover.init()
  59. createFilePopover.contentViewController = vc
  60. createFilePopover.animates = true
  61. createFilePopover.behavior = .semitransient
  62. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  63. createFilePopover.show(relativeTo: CGRect(x: sender.bounds.origin.x, y: -10, width: sender.bounds.size.width, height: sender.bounds.size.height), of: sender, preferredEdge: .maxY)
  64. vc.customBoxWidthLayoutConstraint.constant = self.popWidth ?? sender.frame.width
  65. vc.downCallback = { [weak self](downEntered: Bool, count: String) -> Void in
  66. if downEntered {
  67. if self != nil {
  68. if self!.mouseDownAction != nil {
  69. self!.mouseDownAction!(sender, count)
  70. }
  71. }
  72. createFilePopover.close()
  73. }
  74. }
  75. } else {
  76. if self.mouseDownAction != nil {
  77. self.mouseDownAction!(sender, "")
  78. }
  79. }
  80. }
  81. }