NibLoadable.swift 793 B

1234567891011121314151617181920212223242526272829
  1. //
  2. // NibLoadable.swift
  3. // PDF Master
  4. //
  5. // Created by Niehaoyu on 2022/10/25.
  6. //
  7. import Foundation
  8. protocol NibLoadable {
  9. static var nibName: String? { get }
  10. static func createFromNib(in bundle: Bundle) -> Self?
  11. }
  12. extension NibLoadable where Self: NSView {
  13. static var nibName: String? {
  14. return String(describing: Self.self)
  15. }
  16. static func createFromNib(in bundle: Bundle = Bundle.main) -> Self? {
  17. guard let nibName = nibName else { return nil }
  18. var topLevelArray: NSArray? = nil
  19. bundle.loadNibNamed(NSNib.Name(nibName), owner: self, topLevelObjects: &topLevelArray)
  20. guard let results = topLevelArray else { return nil }
  21. let views = Array<Any>(results).filter { $0 is Self }
  22. return views.last as? Self
  23. }
  24. }