Skip to content

Instantly share code, notes, and snippets.

@PaulTaykalo
Last active November 24, 2017 17:55
Show Gist options
  • Save PaulTaykalo/5cc514ee387897acfb4e5a030303db0b to your computer and use it in GitHub Desktop.
Save PaulTaykalo/5cc514ee387897acfb4e5a030303db0b to your computer and use it in GitHub Desktop.
class UICollectionViewListRenderer: ListRenderer {
private var ignoringUpdates: Bool = false
weak var collectionView: UICollectionView?
init(collectionView: UICollectionView?) {
self.collectionView = collectionView
}
func reloadData() {
collectionView?.reloadData()
}
func reloadSections(_ sections: [Int]) {
guard !ignoringUpdates else { return }
modify { $0.reloadSections(IndexSet(sections)) }
}
func deleteSections(_ sections: [Int]) {
modify { $0.deleteSections(IndexSet(sections)) }
}
func insertSections(_ sections: [Int]) {
modify { $0.insertSections(IndexSet(sections)) }
}
func reloadItems(at indexPaths: [IndexPath]) {
guard !ignoringUpdates else { return }
modify { $0.reloadItems(at: indexPaths) }
}
func insertItems(at indexPaths: [IndexPath]) {
modify { $0.insertItems(at: indexPaths) }
}
func deleteItems(at indexPaths: [IndexPath]) {
modify { $0.deleteItems(at: indexPaths) }
}
/// Runs modification update on collection view if collection view is visible
/// If collection view is not present on window= it ignores update and just calls reloadData(
/// - Parameter action: mofidictaion action
private func modify(_ action: (UICollectionView) -> ()) {
guard let collectionView = collectionView, collectionView.window != nil else { reloadData(); return }
action(collectionView)
}
func withIgnoringUpdates(block: () -> ()) {
ignoringUpdates = true
block()
ignoringUpdates = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment