Skip to content

Instantly share code, notes, and snippets.

@erikfloresq
Last active July 13, 2024 14:25
Show Gist options
  • Save erikfloresq/82f9ebdbf4b943063f0e145d4009333c to your computer and use it in GitHub Desktop.
Save erikfloresq/82f9ebdbf4b943063f0e145d4009333c to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
let tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(ItemCell.self, forCellReuseIdentifier: "ItemCell")
return tableView
}()
lazy var tableViewDataSource = TableViewDataSource(tableView: tableView)
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
let item = UIBarButtonItem(image: .add, style: .plain, target: self, action: #selector(addItem))
navigationItem.rightBarButtonItem = item
tableViewDataSource.snapshotData(items: (1...2).map{ Item(text: "Demo \($0)") })
}
@objc
func addItem() {
let item = Item(text: "demo")
tableViewDataSource.snapshotData(items: [item])
}
}
class ItemCell: UITableViewCell {
override var reuseIdentifier: String? {
"ItemCell"
}
}
struct Item: Hashable, Identifiable {
let id: UUID = UUID()
let text: String
}
class TableViewDataSource {
enum Section {
case main
}
typealias DataSource = UITableViewDiffableDataSource<Section, Item>
typealias Snapshot = NSDiffableDataSourceSnapshot<Section, Item>
private let tableView: UITableView
var snapshot = Snapshot()
lazy var dataSource = DataSource(tableView: tableView) { tableView, indexPath, itemIdentifier in
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
var config = cell.defaultContentConfiguration()
config.text = itemIdentifier.text
cell.contentConfiguration = config
return cell
}
init(tableView: UITableView) {
self.tableView = tableView
snapshot.appendSections([.main])
}
func snapshotData(items: [Item]) {
snapshot.appendItems(items, toSection: .main)
dataSource.apply(snapshot)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment