BaseXibView.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. updateUIThemeColor()
  42. updateUILanguage()
  43. }
  44. private func initContentView() {
  45. let isExist = Bundle.main.path(forResource: String(describing:self.classForCoder.self), ofType: "nib")
  46. if isExist != nil {
  47. var topLevelArray: NSArray? = nil
  48. let resource = NSNib(nibNamed: String(describing:self.classForCoder.self), bundle: Bundle(for: self.classForCoder.self))
  49. if resource != nil {
  50. if (resource!.instantiate(withOwner: self, topLevelObjects: &topLevelArray)) {
  51. for view in topLevelArray! {
  52. if view is NSView {
  53. contentView = view as? NSView
  54. break
  55. }
  56. }
  57. }
  58. if contentView == nil {
  59. contentView = NSView()
  60. }
  61. addSubview(contentView)
  62. contentView.translatesAutoresizingMaskIntoConstraints = false
  63. NSLayoutConstraint.activate([
  64. contentView.topAnchor.constraint(equalTo: topAnchor),
  65. contentView.leftAnchor.constraint(equalTo: leftAnchor),
  66. contentView.rightAnchor.constraint(equalTo: rightAnchor),
  67. contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
  68. contentView.updateConstraintsForSubtreeIfNeeded()
  69. }
  70. }
  71. }
  72. }