Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. //
  2. // Reusable.swift
  3. //
  4. // Created by Zef Houssney
  5. //
  6.  
  7. import UIKit
  8.  
  9. protocol Reusable {
  10. static var reuseIdentifier: String { get }
  11. }
  12.  
  13. extension Reusable {
  14. static var reuseIdentifier: String {
  15. return String(describing: self)
  16. }
  17. }
  18.  
  19. extension UITableViewCell: Reusable { }
  20. extension UICollectionReusableView: Reusable { }
  21. extension UITableViewHeaderFooterView: Reusable { }
  22.  
  23. extension UICollectionView {
  24. func register(cellType type: UICollectionViewCell.Type) {
  25. register(type, forCellWithReuseIdentifier: type.reuseIdentifier)
  26. }
  27.  
  28. func registerNib(cellType type: UICollectionViewCell.Type) {
  29. register(UINib(nibName: type.reuseIdentifier, bundle: nil), forCellWithReuseIdentifier: type.reuseIdentifier)
  30. }
  31.  
  32. func dequeueCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T {
  33. guard let cell = dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
  34. fatalError("You need to register cell of type `\(T.reuseIdentifier)`")
  35. }
  36.  
  37. return cell
  38. }
  39.  
  40. func registerSupplementaryView(suplementaryViewType type: UICollectionReusableView.Type, kind: String) {
  41. register(type, forSupplementaryViewOfKind: kind, withReuseIdentifier: type.reuseIdentifier)
  42. }
  43.  
  44. func dequeueSupplementaryView<T: UICollectionReusableView>(ofKind elementKind: String, for indexPath: IndexPath) -> T {
  45. guard let supplementaryView = dequeueReusableSupplementaryView(
  46. ofKind: elementKind,
  47. withReuseIdentifier: T.reuseIdentifier,
  48. for: indexPath) as? T else {
  49. fatalError("You need to register supplementaryView of type `\(T.reuseIdentifier)` for kind `\(elementKind)`")
  50. }
  51. return supplementaryView
  52. }
  53. }
  54.  
  55. extension UITableView {
  56. func register(cellType type: UITableViewCell.Type) {
  57. register(type, forCellReuseIdentifier: type.reuseIdentifier)
  58. }
  59.  
  60. func registerNib(cellType type: UITableViewCell.Type) {
  61. register(UINib(nibName: type.reuseIdentifier, bundle: nil), forCellReuseIdentifier: type.reuseIdentifier)
  62. }
  63.  
  64. func dequeueCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
  65. guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
  66. fatalError("You need to register cell of type `\(T.reuseIdentifier)`")
  67. }
  68.  
  69. return cell
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement