UICollectionView+ReusableKit.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #if os(iOS)
  2. import UIKit
  3. /// An enumeration that represents UICollectionView supplementary view kind.
  4. public enum SupplementaryViewKind: String {
  5. case header, footer
  6. public init?(rawValue: String) {
  7. switch rawValue {
  8. case UICollectionView.elementKindSectionHeader: self = .header
  9. case UICollectionView.elementKindSectionFooter: self = .footer
  10. default: return nil
  11. }
  12. }
  13. public var rawValue: String {
  14. switch self {
  15. case .header: return UICollectionView.elementKindSectionHeader
  16. case .footer: return UICollectionView.elementKindSectionFooter
  17. }
  18. }
  19. }
  20. extension UICollectionViewCell: CellType {
  21. }
  22. extension UIView: ViewType {
  23. }
  24. extension UICollectionView {
  25. // MARK: Cell
  26. /// Registers a generic cell for use in creating new collection view cells.
  27. public func register<Cell>(_ cell: ReusableCell<Cell>) {
  28. if let nib = cell.nib {
  29. self.register(nib, forCellWithReuseIdentifier: cell.identifier)
  30. } else {
  31. self.register(Cell.self, forCellWithReuseIdentifier: cell.identifier)
  32. }
  33. }
  34. /// Returns a generic reusable cell located by its identifier.
  35. public func dequeue<Cell>(_ cell: ReusableCell<Cell>, for indexPath: IndexPath) -> Cell {
  36. return self.dequeueReusableCell(withReuseIdentifier: cell.identifier, for: indexPath) as! Cell
  37. }
  38. // MARK: Supplementary View
  39. /// Registers a generic view for use in creating new supplementary views for the collection view.
  40. public func register<View>(_ view: ReusableView<View>, kind: SupplementaryViewKind) {
  41. self.register(view, kind: kind.rawValue)
  42. }
  43. /// Registers a generic view for use in creating new supplementary views for the collection view.
  44. public func register<View>(_ view: ReusableView<View>, kind: String) {
  45. if let nib = view.nib {
  46. self.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: view.identifier)
  47. } else {
  48. self.register(View.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: view.identifier)
  49. }
  50. }
  51. /// Returns a generic reusable supplementary view located by its identifier and kind.
  52. public func dequeue<View>(_ view: ReusableView<View>, kind: String, for indexPath: IndexPath) -> View {
  53. return self.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: view.identifier, for: indexPath) as! View
  54. }
  55. /// Returns a generic reusable supplementary view located by its identifier and kind.
  56. public func dequeue<View>(_ view: ReusableView<View>, kind: SupplementaryViewKind, for indexPath: IndexPath) -> View {
  57. return self.dequeue(view, kind: kind.rawValue, for: indexPath)
  58. }
  59. }
  60. #endif