BaseXibView.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // BaseXibView.swift
  3. // KMComponentLibrary
  4. //
  5. // Created by wanjun on 2024/6/6.
  6. //
  7. import Cocoa
  8. import AppKit
  9. @objcMembers
  10. public class BaseXibView: NSView {
  11. @IBOutlet var contentView: NSView!
  12. deinit {
  13. KMPrint(self.className + " deinit.")
  14. self.removeNotifations()
  15. }
  16. // MARK: 初始化
  17. public required init?(coder decoder: NSCoder) {
  18. super.init(coder: decoder)
  19. initContentView()
  20. addNotifations()
  21. setup()
  22. }
  23. override init(frame frameRect: NSRect) {
  24. super.init(frame: frameRect)
  25. initContentView()
  26. addNotifations()
  27. setup()
  28. }
  29. private func addNotifations() {
  30. updateUIThemeColor()
  31. NotificationCenter.default.addObserver(self, selector: #selector(updateUIThemeColor), name: APPAppearanceChangedNotificationName, object: nil)
  32. updateUILanguage()
  33. NotificationCenter.default.addObserver(self, selector: #selector(updateUILanguage), name: APPLanguageChangedNotificationName, object: nil)
  34. }
  35. private func removeNotifations() {
  36. NotificationCenter.default.removeObserver(self)
  37. }
  38. @objc func updateUIThemeColor() {}
  39. @objc func updateUILanguage() {}
  40. @objc func setup() {}
  41. private func initContentView() {
  42. let isExist = Bundle.main.path(forResource: String(describing:self.classForCoder.self), ofType: "nib")
  43. if isExist != nil {
  44. var topLevelArray: NSArray? = nil
  45. let resource = NSNib(nibNamed: String(describing:self.classForCoder.self), bundle: Bundle(for: self.classForCoder.self))
  46. if resource != nil {
  47. if (resource!.instantiate(withOwner: self, topLevelObjects: &topLevelArray)) {
  48. for view in topLevelArray! {
  49. if view is NSView {
  50. contentView = view as? NSView
  51. break
  52. }
  53. }
  54. }
  55. if contentView == nil {
  56. contentView = NSView()
  57. }
  58. addSubview(contentView)
  59. contentView.translatesAutoresizingMaskIntoConstraints = false
  60. NSLayoutConstraint.activate([
  61. contentView.topAnchor.constraint(equalTo: topAnchor),
  62. contentView.leftAnchor.constraint(equalTo: leftAnchor),
  63. contentView.rightAnchor.constraint(equalTo: rightAnchor),
  64. contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
  65. contentView.updateConstraintsForSubtreeIfNeeded()
  66. }
  67. }
  68. }
  69. }