首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITableViewDiffableDataSource无效区段

UITableViewDiffableDataSource无效区段
EN

Stack Overflow用户
提问于 2020-03-21 15:03:21
回答 3查看 1.5K关注 0票数 6

我试着使用UITableViewDiffableDataSource

代码语言:javascript
复制
class SecondViewController: UIViewController {

    enum Section {
        case main
    }

    struct Model: Hashable {
        let title: String
    }

    var tableView: UITableView!
    var dataSource: UITableViewDiffableDataSource<Section, Model>!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView = UITableView(frame: view.bounds)
        view.addSubview(tableView)
        tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        view.layoutIfNeeded()

        dataSource = UITableViewDiffableDataSource<Section, Model>(tableView: tableView, cellProvider: { (tableView, indexPath, item) -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            cell.textLabel?.text = item.title
            return cell
        })

        var snapshot = NSDiffableDataSourceSnapshot<Section, Model>()
        snapshot.appendSections([.main])
        snapshot.appendItems([Model(title: "1")], toSection: .main)
        dataSource.apply(snapshot)
    }
}

如果在创建view.layoutIfNeeded()之前使用dataSource,它将崩溃:

由于

异常“NSInternalInconsistencyException”终止应用程序,原因:“无效更新:无效节数。更新(1)后表视图中包含的节数必须等于更新(1)之前表视图中包含的节数,加上或减去插入或删除的节数(插入或删除的节数)。”

EN

回答 3

Stack Overflow用户

发布于 2020-07-25 03:20:05

在使用来自UITableView的结果填充PassthroughSubject时,在显示UIViewController时,我也遇到了同样的问题。

动画更新对我来说非常重要,所以我的解决方法是首先“优化”DiffableDataSource,在初始化后立即创建快照,追加我想要的部分,用空数组追加项目,并将快照应用于animatingDifferences: false

之后,我能够应用无问题的数据动画快照。

票数 7
EN

Stack Overflow用户

发布于 2021-12-15 22:48:51

我也遇到了同样的问题。通常,在iOS 14上,在表视图的数据源设置之前导致布局会导致崩溃。

一旦创建了表视图,就可以通过设置数据源来修复这些崩溃。如果您想要动画您的初始快照,那么首先设置一个空快照,然后使用animatingDifferences: true填充的快照。

票数 0
EN

Stack Overflow用户

发布于 2022-05-19 05:30:46

同样的问题,我发现即使没有动画,一些用户在生产中仍然会崩溃。

当我在setupUI in viewDidLoadDispatchQueue.main.async帮助我解决这个问题

代码语言:javascript
复制
    DispatchQueue.main.async { [weak self] in
        guard let self = self else { return }
        var snapshot = NSDiffableDataSourceSnapshot<Section, Row>()
        snapshot.appendSections([...])
        snapshot.appendItems([...], toSection: .main)
        
        dataSource.apply(snapshot, animatingDifferences: true, completion: nil)            
    }

更具体地说,仅仅将animatingDifferences设置为false仍然会崩溃。此崩溃仅发生在iOS 15.0.0和iOS 15.0.1上。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60789365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档