美文网首页iOS经验总结
UITableViewDiffableDataSource和UI

UITableViewDiffableDataSource和UI

作者: CodingTom | 来源:发表于2021-12-16 10:48 被阅读0次

在 iOS 平台上是 UITableViewDiffableDataSource 和 UICollectionViewDiffableDataSource

用来替代 UITableView 或者 UICollectionView的datasource属性,

通过设置新的DataSource可以做到有更新动画,自动插入更新等。

更新数据的方法:此方法 不用自己调用reload ,调用对象的apply 方法后页面会自动更新。

保证了数据和UI的一致问题

self.dataSource.apply(currentSnapshot, animatingDifferences: true)

UITableView 设置数据源

    func configDataSource() {
        self.dataSource = UITableViewDiffableDataSource<Section, Item>.init(tableView: self.tableView, cellProvider: {(tableView, indexPath, item) -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: ViewController.reuseIdentifier, for: indexPath)
            var content = cell.defaultContentConfiguration()
            content.text = item.title
            cell.contentConfiguration = content
            return cell
        })
        self.dataSource.defaultRowAnimation = .fade
    }

添加数据

    func updateUI() {
        currentSnapshot = NSDiffableDataSourceSnapshot<Section, Item>()
        currentSnapshot.appendSections([.main])
        currentSnapshot.appendItems(mainItems, toSection: .main)
        self.dataSource.apply(currentSnapshot, animatingDifferences: true)
    }

参考资料:

https://developer.apple.com/documentation/uikit/uicollectionview/cellregistration

https://www.jianshu.com/p/e4f02b0903af

https://juejin.cn/post/6875312577698594829

相关文章

网友评论

    本文标题:UITableViewDiffableDataSource和UI

    本文链接:https://www.haomeiwen.com/subject/viamfrtx.html