CellFrameCacheContainer.swift 1.0 KB

123456789101112131415161718192021222324252627282930
  1. //
  2. // CellFrameCacheContainer.swift
  3. // TwidereX
  4. //
  5. // Created by Cirno MainasuK on 2021-10-13.
  6. // Copyright © 2021 Twidere. All rights reserved.
  7. //
  8. import UIKit
  9. protocol CellFrameCacheContainer {
  10. var cellFrameCache: NSCache<NSNumber, NSValue> { get }
  11. func keyForCache(tableView: UITableView, indexPath: IndexPath) -> NSNumber?
  12. }
  13. extension CellFrameCacheContainer {
  14. func cacheCellFrame(tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  15. guard let key = keyForCache(tableView: tableView, indexPath: indexPath) else { return }
  16. let value = NSValue(cgRect: cell.frame)
  17. cellFrameCache.setObject(value, forKey: key)
  18. }
  19. func retrieveCellFrame(tableView: UITableView, indexPath: IndexPath) -> CGRect? {
  20. guard let key = keyForCache(tableView: tableView, indexPath: indexPath) else { return nil }
  21. guard let frame = cellFrameCache.object(forKey: key)?.cgRectValue else { return nil }
  22. return frame
  23. }
  24. }