【问题标题】:How to add Header Name in UITableViewDiffableDataSource如何在 UITableViewDiffableDataSource 中添加标题名称
【发布时间】:2020-01-30 16:15:57
【问题描述】:

我尝试在UITableView 中为每个部分添加标题标题,但在本例中为UITableViewDiffableDataSource,我不知道应该在哪里做。我的代码的一部分:

private func prepareTableView() {
    tableView.delegate = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    dataSource = UITableViewDiffableDataSource<Sections, User>(tableView: tableView, cellProvider: { (tableView, indexPath, user) -> UITableViewCell? in
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = user.name
        return cell
    })
}

private func addElement(_ user: User) {
    var snap = NSDiffableDataSourceSnapshot<Sections, User>()
    snap.appendSections([.main, .second])
    if isFirst {
        users.append(user)
    } else {
        secondUsers.append(user)
    }
    snap.appendItems(users, toSection: .main)
    snap.appendItems(secondUsers, toSection: .second)
    isFirst.toggle()
    dataSource.apply(snap, animatingDifferences: true, completion: nil)
    dataSource.defaultRowAnimation = .fade
}

UICollectionViewDiffableDataSource 有一个参数supplementaryViewProvider,用户可以在其中配置标头。 UITableViewDiffableDataSource中确实存在这样的东西

【问题讨论】:

    标签: swift uitableview diffabledatasource nsdiffabledatasourcesnapshot


    【解决方案1】:

    我可以通过像这样子类化 UITableViewDiffableDataSource 类来做到这一点:

    class MyDataSource: UITableViewDiffableDataSource<Sections, User> {
    
        override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return "Hello, World!"
        }
    }
    
    

    然后在你的代码中而不是这个:

    dataSource = UITableViewDiffableDataSource<Sections, User>
    

    使用您自己的数据源类:

    dataSource = MyDataSource<Sections, User>
    

    【讨论】:

      【解决方案2】:

      是的,查看UICollectionViewDiffableDataSourcesupplementaryViewProvider 属性

      Apple 并没有太多 documentation,但您可以使用类似于初始化 diffable 数据源本身的方式来初始化它。它返回一个UICollectionReusableView,它可以是通用视图,也可以是您的页眉或页脚视图子类之一。

      【讨论】:

      • 问题是关于 UITableViewDiffableDataSource 而不是 Collection 视图
      猜你喜欢
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 2019-07-20
      • 2017-01-05
      • 2016-12-07
      • 2020-02-22
      • 2014-11-05
      • 1970-01-01
      相关资源
      最近更新 更多