import UIKit
enum Section {
case today
}
struct Note : Hashable {
var idx : Int
var content : String
}
class ViewController: UIViewController {
private var dataSource: UITableViewDiffableDataSource<Section, Note>!
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self))
self.view.addSubview(tableView)
return tableView
}()
override func loadView() {
super.loadView()
self.tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
let noteList = [
Note(idx:0, content:"0"),
Note(idx:1, content:"1"),
Note(idx:2, content:"2"),
Note(idx:3, content:"4")
]
self.dataSource = getDataSource()
updateData(noteList)
}
//1.使用 DiffableDataSource 配置当前 UITableView 的数据源, 生成UITableViewDiffableDataSource数据源
func getDataSource() -> UITableViewDiffableDataSource<Section, Note>? {
return UITableViewDiffableDataSource(tableView: self.tableView) { (tableView, indexPath, note) -> UITableViewCell? in
let cell = UITableViewCell()
cell.textLabel?.text = note.content
return cell
}
}
//2.使用snapshot对dataSource进行差异化比对,进行动态更新。避免了之前的复杂的维护过程
func updateData(_ noteList: [Note]) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Note>()
snapshot.appendSections([.today])
snapshot.appendItems(noteList)
//3.使用修改后的新数据snapshot,传入apply方法内,让新旧数据进行对比,然后在内部对变更后的差异数据源进行更新。
//DiffableDataSource 通过调用自身 apply 方法将 DataSourceSnapshot 变更后的数据更新同步到 UITableView。
self.dataSource.apply(snapshot, animatingDifferences: false, completion: nil)
}
}