KMCropTipView.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // KMCropTipView.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2023/1/4.
  6. //
  7. import Cocoa
  8. typealias KMCropTipViewEnterAction = ()->()
  9. class KMCropTipView: NSView {
  10. private var contentView = NSView()
  11. private var label = NSTextField(labelWithString: "")
  12. private var localMonitor: Any!
  13. var enterAction: KMCropTipViewEnterAction!
  14. deinit {
  15. NSEvent.removeMonitor(self.localMonitor as Any)
  16. self.localMonitor = nil
  17. }
  18. override init(frame frameRect: NSRect) {
  19. super.init(frame: frameRect)
  20. initSubviews()
  21. }
  22. required init?(coder: NSCoder) {
  23. super.init(coder: coder)
  24. initSubviews()
  25. }
  26. func initSubviews() {
  27. self.addSubview(self.contentView)
  28. self.contentView.addSubview(self.label)
  29. self.contentView.wantsLayer = true
  30. self.contentView.layer?.backgroundColor = NSColor(red: 17.0/255.0, green: 138.0/255.0, blue: 1.0, alpha: 1.0).cgColor
  31. self.label.textColor = NSColor.white
  32. self.label.font = NSFont.systemFont(ofSize: 14)
  33. self.label.alignment = .center
  34. self.localMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyUp, handler: {
  35. [weak self] (event: NSEvent) -> NSEvent in
  36. if (event.keyCode != 36) {
  37. return event
  38. }
  39. guard let callback = self!.enterAction else {
  40. return event
  41. }
  42. callback()
  43. return event
  44. })
  45. }
  46. override func layout() {
  47. super.layout()
  48. let width: CGFloat = NSWidth(self.bounds)
  49. let height: CGFloat = NSHeight(self.bounds)
  50. let contentWidth: CGFloat = 186
  51. let contentHeight: CGFloat = 32
  52. self.contentView.frame = NSMakeRect((width-contentWidth)*0.5, (height-contentHeight)*0.5, contentWidth, contentHeight)
  53. self.label.frame = NSMakeRect(0, 5, contentWidth, 22)
  54. }
  55. func setString(string: String) {
  56. self.label.stringValue = string
  57. }
  58. }