KMBaseViewController.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // KMBaseViewController.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2023/5/5.
  6. //
  7. import Cocoa
  8. // 基类 [抽象类]
  9. class KMBaseViewController: NSViewController {
  10. // 是否需要菜单
  11. var needMenu = false {
  12. didSet {
  13. if (self.needMenu) {
  14. self.addMenu(to: self.view)
  15. } else {
  16. self.removeMenu(to: self.view)
  17. }
  18. }
  19. }
  20. override func viewDidLoad() {
  21. super.viewDidLoad()
  22. if (self.needMenu) {
  23. self.addMenu(to: self.view)
  24. } else {
  25. self.removeMenu(to: self.view)
  26. }
  27. }
  28. // MARK: - Menu Add & Remove
  29. public func addMenu(to view: NSView?) {
  30. if let menuView = view {
  31. self.addMenu(to: menuView)
  32. return
  33. }
  34. self.addMenu(to: self.view)
  35. }
  36. public func removeMenu(to view: NSView?) {
  37. if let menuView = view {
  38. self.removeMenu(to: menuView)
  39. return
  40. }
  41. self.removeMenu(to: self.view)
  42. }
  43. private func addMenu(to view: NSView) {
  44. // 先移除
  45. self.removeMenu(to: view)
  46. let menu = NSMenu()
  47. menu.delegate = self
  48. view.menu = menu
  49. }
  50. private func removeMenu(to view: NSView) {
  51. view.menu?.delegate = nil
  52. view.menu = nil
  53. }
  54. }
  55. extension KMBaseViewController: NSMenuDelegate, NSMenuItemValidation {
  56. func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  57. return true
  58. }
  59. func menuNeedsUpdate(_ menu: NSMenu) {
  60. menu.removeAllItems()
  61. }
  62. }