首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITableViewDiffableDataSource:如何获得节索引

UITableViewDiffableDataSource:如何获得节索引
EN

Stack Overflow用户
提问于 2019-08-19 17:47:51
回答 2查看 820关注 0票数 2

我正在尝试采用新的iOS 13 UITableViewDiffableDataSource,但遇到了困难;我无法工作如何实现

代码语言:javascript
复制
func sectionIndexTitles(for tableView: UITableView) -> [String]?

这是一个数据源方法,而不是委托方法。因此,既然数据源是UITableViewDiffableDataSource,它就需要实现该方法。但事实并非如此。

我尝试将UITableViewDiffableDataSource子类化并添加sectionIndexTitles的实现,但我的实现从未被调用过:

代码语言:javascript
复制
class MyDataSource : UITableViewDiffableDataSource<String,String> {
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.snapshot().sectionIdentifiers // not called
    }
}

有人解决过这个问题吗?为了以防万一,我会把它归档为窃听器。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-23 20:07:20

您需要子类UITableViewDiffableDataSource,然后覆盖

代码语言:javascript
复制
func sectionIndexTitles(for tableView: UITableView) 

独自一人。

但是,要启用索引的功能,还必须覆盖

代码语言:javascript
复制
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int)

下面是我如何实现它的一个例子:

代码语言:javascript
复制
import UIKit
import MediaPlayer

class TableViewDiffableDataSource: UITableViewDiffableDataSource<String, MPMediaItemCollection> {
    var sectionTitles = [String]()

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return sectionTitles
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionTitles[section]
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return sectionTitles.firstIndex(of: title) ?? 0
    }
}

功劳属于史蒂夫·布林,他带领我走向了正确的方向。

票数 3
EN

Stack Overflow用户

发布于 2020-06-11 19:08:35

self.dataSource插入到UITableViewDiffableDataSource (将自身设置为tableView.dataSource)之后,将tableView.dataSource设置为self,即UITableViewController子类。现在,在您的numberOfSectionsInTableViewnumberOfRowsInSection方法中,将这些方法转发到self.dataSource并返回其信息(这是组合模式)。现在,您的UITableViewController只是正常地实现它的节标题,因为它是表的数据源。

我认为,如果已经设置了UITableViewDiffableDataSource,则不应该将自己设置为dataSource,但我想他们设计它的目的是以最容易出错的方式工作,因为在故事板中添加了UITableViewController,默认情况下它被设置为dataSourcedelegate

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

https://stackoverflow.com/questions/57561664

复制
相关文章

相似问题

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