首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在UITableViewDiffableDataSource中添加头部名称

如何在UITableViewDiffableDataSource中添加头部名称
EN

Stack Overflow用户
提问于 2019-10-01 19:12:50
回答 2查看 1.8K关注 0票数 3

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

代码语言:javascript
复制
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,用户可以在其中配置headers。在UITableViewDiffableDataSource中是否存在类似这样的东西

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-28 05:53:50

我能够做到这一点,方法是将UITableViewDiffableDataSource类派生为如下所示:

代码语言:javascript
复制
class MyDataSource: UITableViewDiffableDataSource<Sections, User> {

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Hello, World!"
    }
}

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

代码语言:javascript
复制
dataSource = UITableViewDiffableDataSource<Sections, User>

使用您自己的数据源类:

代码语言:javascript
复制
dataSource = MyDataSource<Sections, User>
票数 14
EN

Stack Overflow用户

发布于 2020-01-17 23:28:46

是,请参阅UICollectionViewDiffableDataSourcesupplementaryViewProvider属性

苹果实际上并没有太多的documentation,但是你可以用一个闭包来初始化它,就像你初始化可区分数据源本身一样。它返回一个UICollectionReusableView,它可以是泛型视图,也可以是页眉或页脚视图子类之一。

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

https://stackoverflow.com/questions/58183637

复制
相关文章

相似问题

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