Skip to content

Instantly share code, notes, and snippets.

@manmal
Last active March 14, 2019 12:59
Show Gist options
  • Save manmal/eb43a283cc9f7593da1d2d0e8c166440 to your computer and use it in GitHub Desktop.
Save manmal/eb43a283cc9f7593da1d2d0e8c166440 to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
class CachedItemHeightDatasource: NSObject, UITableViewDelegate, UITableViewDataSource {
var heightAtIndexPath: [IndexPath: CGFloat] = [:]
let tableView: UITableView
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return heightAtIndexPath[indexPath] ?? UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
heightAtIndexPath[indexPath] = cell.frame.size.height
}
func update(rowAt indexPath: IndexPath) {
tableView.beginUpdates()
heightAtIndexPath[indexPath] = nil
reloadRows(at: [indexPath], with: .automatic) // fetches new cell via tableView(_:cellForRowAt:)
tableView.endUpdates()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment