Last active
August 28, 2018 19:22
-
-
Save danielt1263/893983ca81070cf9b8b18630c678e3be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UITableViewExtensions.swift | |
// | |
// Created by Daniel Tartaglia on 7/21/17. | |
// Copyright © 2017 MIT License. | |
// | |
import UIKit | |
extension UITableView { | |
/// handles animating the updates to a table view. | |
/// - parameter oldData: The array that the collection is currently using in its data source. | |
/// - parameter newData: The new array that the collection should be using. | |
/// - parameter adaptor: A closure that can turn an item into something that is Hashable. If the item is already hasable, pass in { $0 } | |
/// - parameter assignment: assign your new array into your old array in this closure. | |
func performUpdates<Item, ID: Hashable>(oldData: [Item], newData: [Item], adaptor: (Item) -> ID, assignment: @escaping () -> Void) { | |
if oldData.isEmpty { | |
assignment() | |
reloadData() | |
} | |
else { | |
let oldIDs = oldData.map(adaptor) | |
let newIDs = newData.map(adaptor) | |
self.beginUpdates() | |
let (insertions, deletions) = findDifferences(old: oldIDs, new: newIDs, moveBlock: { (from, to) in | |
self.moveRow(at: IndexPath(row: from, section: 0), to: IndexPath(row: to, section: 0)) | |
}) | |
self.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic) | |
self.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic) | |
assignment() | |
self.endUpdates() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment