NibIdentifiable.swift 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //
  2. // NibIdentifiable.swift
  3. // Bio
  4. //
  5. // Created by Joan Disho on 31.10.17.
  6. // Copyright © 2017 Joan Disho. All rights reserved.
  7. //
  8. import UIKit
  9. protocol NibIdentifiable: class {
  10. static var nib: UINib { get }
  11. }
  12. extension NibIdentifiable {
  13. static var nib: UINib {
  14. return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
  15. }
  16. }
  17. extension NibIdentifiable where Self: UIView {
  18. static func initFromNib() -> Self {
  19. guard let view = nib.instantiate(withOwner: nil, options: nil).first as? Self
  20. else { fatalError("Couldn't find nib file for \(self)") }
  21. return view
  22. }
  23. }
  24. extension NibIdentifiable where Self: UITableView {
  25. static func initFromNib() -> Self {
  26. guard let tableView = nib.instantiate(withOwner: nil, options: nil).first as? Self
  27. else { fatalError("Couldn't find nib file for \(self)") }
  28. return tableView
  29. }
  30. }
  31. extension NibIdentifiable where Self: UICollectionView {
  32. static func initFromNib() -> Self {
  33. guard let collectionView = nib.instantiate(withOwner: nil, options: nil).first as? Self
  34. else { fatalError("Couldn't find nib file for \(self)") }
  35. return collectionView
  36. }
  37. }
  38. extension NibIdentifiable where Self: UIViewController {
  39. static func initFromNib() -> Self {
  40. return Self(nibName: nibIdentifier, bundle: nil)
  41. }
  42. }
  43. extension UIViewController: NibIdentifiable {
  44. static var nibIdentifier: String {
  45. return String(describing: self)
  46. }
  47. }