NibLoadable.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*********************************************
  2. *
  3. * This code is under the MIT License (MIT)
  4. *
  5. * Copyright (c) 2016 AliSoftware
  6. *
  7. *********************************************/
  8. import UIKit
  9. // MARK: Protocol Definition
  10. /// Make your UIView subclasses conform to this protocol when:
  11. /// * they *are* NIB-based, and
  12. /// * this class is used as the XIB's root view
  13. ///
  14. /// to be able to instantiate them from the NIB in a type-safe manner
  15. public protocol NibLoadable: class {
  16. /// The nib file to use to load a new instance of the View designed in a XIB
  17. static var nib: UINib { get }
  18. }
  19. // MARK: Default implementation
  20. public extension NibLoadable {
  21. /// By default, use the nib which have the same name as the name of the class,
  22. /// and located in the bundle of that class
  23. static var nib: UINib {
  24. return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
  25. }
  26. }
  27. // MARK: Support for instantiation from NIB
  28. public extension NibLoadable where Self: UIView {
  29. /**
  30. Returns a `UIView` object instantiated from nib
  31. - returns: A `NibLoadable`, `UIView` instance
  32. */
  33. static func loadFromNib() -> Self {
  34. guard let view = nib.instantiate(withOwner: nil, options: nil).first as? Self else {
  35. fatalError("The nib \(nib) expected its root view to be of type \(self)")
  36. }
  37. return view
  38. }
  39. }