Skip to content

Instantly share code, notes, and snippets.

@possen
Last active June 21, 2020 23:32
Show Gist options
  • Save possen/cdcb3f83a63a008fa0185cf066922a92 to your computer and use it in GitHub Desktop.
Save possen/cdcb3f83a63a008fa0185cf066922a92 to your computer and use it in GitHub Desktop.
Minimal UITableViewDiffableDataSource Playground
//
// Minimal code to get Diffable Data Sources working in a Playground.
// Easier to understand than the WWDC examples.
//
// Paul Ossenbruggen
//
import UIKit
import PlaygroundSupport
let list = [
"hello",
"goodbye",
"goodluck"
]
let list2 = [
"ok",
"done"
]
class ViewController: UITableViewController {
enum Section: CaseIterable {
case main
}
enum ItemType {
case main
}
struct Item: Hashable {
let title: String
private let identifier = UUID()
func hash(into hasher: inout Hasher) {
hasher.combine(self.identifier)
}
}
static let reuseID = "Cell"
var currentSnapshot: NSDiffableDataSourceSnapshot<Section, Item>! = nil
var dataSource: UITableViewDiffableDataSource<Section, Item>! = nil
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Self.reuseID)
dataSource = UITableViewDiffableDataSource<Section, Item>(tableView: tableView) { tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: Self.reuseID, for: indexPath)
print(item.title)
cell.textLabel?.text = item.title
return cell
}
let items = list.map { Item(title: $0) }
currentSnapshot = NSDiffableDataSourceSnapshot<Section, Item>()
currentSnapshot.appendSections([.main])
currentSnapshot.appendItems(items, toSection: .main)
dataSource.apply(currentSnapshot, animatingDifferences: true)
let items2 = list2.map { Item(title: $0) }
currentSnapshot.appendItems(items2, toSection: .main)
dataSource.apply(currentSnapshot, animatingDifferences: true)
currentSnapshot.deleteItems([items[2]])
dataSource.apply(currentSnapshot, animatingDifferences: true)
}
}
let viewController = ViewController()
PlaygroundPage.current.setLiveView(viewController)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment