ReusableKit.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #if os(iOS)
  2. import UIKit
  3. public protocol CellType: class {
  4. var reuseIdentifier: String? { get }
  5. }
  6. /// A generic class that represents reusable cells.
  7. public struct ReusableCell<Cell: CellType> {
  8. public typealias Class = Cell
  9. public let `class`: Class.Type = Class.self
  10. public let identifier: String
  11. public let nib: UINib?
  12. /// Create and returns a new `ReusableCell` instance.
  13. ///
  14. /// - parameter identifier: A reuse identifier. Use random UUID string if identifier is not provided.
  15. /// - parameter nib: A `UINib` instance. Use this when registering from xib.
  16. public init(identifier: String? = nil, nib: UINib? = nil) {
  17. self.identifier = nib?.instantiate(withOwner: nil, options: nil).lazy
  18. .compactMap { ($0 as? CellType)?.reuseIdentifier }
  19. .first ?? identifier ?? UUID().uuidString
  20. self.nib = nib
  21. }
  22. /// A convenience initializer.
  23. ///
  24. /// - parameter identifier: A reuse identifier. Use random UUID string if identifier is not provided.
  25. /// - parameter nibName: A name of nib.
  26. public init(identifier: String? = nil, nibName: String) {
  27. let nib = UINib(nibName: nibName, bundle: nil)
  28. self.init(identifier: identifier, nib: nib)
  29. }
  30. }
  31. public protocol ViewType: class {
  32. }
  33. /// A generic class that represents reusable views.
  34. public struct ReusableView<View: ViewType> {
  35. public typealias Class = View
  36. public let `class`: Class.Type = Class.self
  37. public let identifier: String
  38. public let nib: UINib?
  39. /// Create and returns a new `ReusableView` instance.
  40. ///
  41. /// - parameter identifier: A reuse identifier. Use random UUID string if identifier is not provided.
  42. /// - parameter nib: A `UINib` instance. Use this when registering from xib.
  43. public init(identifier: String? = nil, nib: UINib? = nil) {
  44. self.identifier = identifier ?? UUID().uuidString
  45. self.nib = nib
  46. }
  47. /// A convenience initializer.
  48. ///
  49. /// - parameter identifier: A reuse identifier. Use random UUID string if identifier is not provided.
  50. /// - parameter nibName: A name of nib.
  51. public init(identifier: String? = nil, nibName: String) {
  52. let nib = UINib(nibName: nibName, bundle: nil)
  53. self.init(identifier: identifier, nib: nib)
  54. }
  55. }
  56. #endif