BaseXibView.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  22. override init(frame frameRect: NSRect) {
  23. super.init(frame: frameRect)
  24. initContentView()
  25. addNotifations()
  26. }
  27. private func addNotifations() {
  28. updateUIThemeColor()
  29. NotificationCenter.default.addObserver(self, selector: #selector(updateUIThemeColor), name: APPAppearanceChangedNotificationName, object: nil)
  30. updateUILanguage()
  31. NotificationCenter.default.addObserver(self, selector: #selector(updateUILanguage), name: APPLanguageChangedNotificationName, object: nil)
  32. }
  33. private func removeNotifations() {
  34. NotificationCenter.default.removeObserver(self)
  35. }
  36. @objc func updateUIThemeColor() {}
  37. @objc func updateUILanguage() {}
  38. private func initContentView() {
  39. let isExist = Bundle.main.path(forResource: String(describing:self.classForCoder.self), ofType: "nib")
  40. if isExist != nil {
  41. var topLevelArray: NSArray? = nil
  42. let resource = NSNib(nibNamed: String(describing:self.classForCoder.self), bundle: Bundle(for: self.classForCoder.self))
  43. if resource != nil {
  44. if (resource!.instantiate(withOwner: self, topLevelObjects: &topLevelArray)) {
  45. for view in topLevelArray! {
  46. if view is NSView {
  47. contentView = view as? NSView
  48. break
  49. }
  50. }
  51. }
  52. if contentView == nil {
  53. contentView = NSView()
  54. }
  55. addSubview(contentView)
  56. contentView.translatesAutoresizingMaskIntoConstraints = false
  57. NSLayoutConstraint.activate([
  58. contentView.topAnchor.constraint(equalTo: topAnchor),
  59. contentView.leftAnchor.constraint(equalTo: leftAnchor),
  60. contentView.rightAnchor.constraint(equalTo: rightAnchor),
  61. contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
  62. contentView.updateConstraintsForSubtreeIfNeeded()
  63. }
  64. }
  65. }
  66. }