KMReusable.swift 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. //
  2. // KMReusable.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/11.
  6. //
  7. import Foundation
  8. public protocol KMReusable: AnyObject {
  9. static var identifier: String { get }
  10. static var itemIdentifier: NSUserInterfaceItemIdentifier { get }
  11. }
  12. extension KMReusable {
  13. public static var identifier: String {
  14. return String(describing: Self.self)
  15. }
  16. public static var itemIdentifier: NSUserInterfaceItemIdentifier {
  17. return NSUserInterfaceItemIdentifier(rawValue: self.identifier)
  18. }
  19. }
  20. extension KM where Base: NSCollectionView {
  21. public func register<T: NSCollectionViewItem>(cell: T.Type) where T: KMReusable {
  22. base.register(cell, forItemWithIdentifier: T.itemIdentifier)
  23. }
  24. public func dequeueReusableCell<T: NSCollectionViewItem>(for indexPath: IndexPath) -> T where T: KMReusable {
  25. guard let cell = base.makeItem(withIdentifier: T.itemIdentifier, for: indexPath) as? T else {
  26. fatalError("Could not dequeue reusable cell with identifier: \(T.itemIdentifier)")
  27. }
  28. return cell
  29. }
  30. }