KMEditPDFToolbarView.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // KMEditPDFToolbarView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2024/6/25.
  6. //
  7. import Cocoa
  8. @objc protocol KMEditPDFToolbarViewDelegate: NSObjectProtocol {
  9. @objc optional func numberOfItems(in toolbarView: KMEditPDFToolbarView) -> Int
  10. @objc optional func toolbarView(_ toolbarView: KMEditPDFToolbarView, viewFor index: Int) -> NSView?
  11. @objc optional func toolbarView(_ toolbarView: KMEditPDFToolbarView, sizeForItemAt index: Int) -> NSSize
  12. // @objc optional func toolbarView(_ toolbarView: KMEditPDFToolbarView, insetForSectionAt section: Int) -> NSEdgeInsets
  13. // @objc optional func toolbarView(_ toolbarView: KMEditPDFToolbarView, minimumLineSpacingForSectionAt section: Int) -> CGFloat
  14. // @objc optional func toolbarView(_ toolbarView: KMEditPDFToolbarView, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
  15. }
  16. class KMEditPDFToolbarView: NSView {
  17. weak var delegate: KMEditPDFToolbarViewDelegate?
  18. var itemViews: [NSView] = []
  19. convenience init() {
  20. self.init(frame: .zero)
  21. }
  22. var inset: NSEdgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) {
  23. didSet {
  24. self.needsLayout = true
  25. }
  26. }
  27. func reloadData() {
  28. for sv in self.subviews {
  29. sv.removeFromSuperview()
  30. }
  31. self.itemViews.removeAll()
  32. guard let num = self.delegate?.numberOfItems?(in: self) else {
  33. return
  34. }
  35. for i in 0 ..< num {
  36. if let view = self.delegate?.toolbarView?(self, viewFor: i) {
  37. self.addSubview(view)
  38. self.itemViews.append(view)
  39. }
  40. }
  41. self.needsLayout = true
  42. }
  43. override func layout() {
  44. super.layout()
  45. let height = NSHeight(self.bounds)
  46. let leftMargin = self.inset.left
  47. let topMargin = self.inset.top
  48. var x = leftMargin
  49. let vSpace: CGFloat = 3
  50. for (i, sv) in self.subviews.enumerated() {
  51. if let size = self.delegate?.toolbarView?(self, sizeForItemAt: i) {
  52. let y = topMargin
  53. var frame = NSRect(x: x, y: y, width: size.width, height: size.height)
  54. x += (size.width + vSpace)
  55. sv.frame = frame
  56. }
  57. }
  58. }
  59. }