我正在尝试采用新的iOS 13 UITableViewDiffableDataSource,但遇到了困难;我无法工作如何实现
func sectionIndexTitles(for tableView: UITableView) -> [String]?这是一个数据源方法,而不是委托方法。因此,既然数据源是UITableViewDiffableDataSource,它就需要实现该方法。但事实并非如此。
我尝试将UITableViewDiffableDataSource子类化并添加sectionIndexTitles的实现,但我的实现从未被调用过:
class MyDataSource : UITableViewDiffableDataSource<String,String> {
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return self.snapshot().sectionIdentifiers // not called
}
}有人解决过这个问题吗?为了以防万一,我会把它归档为窃听器。
发布于 2019-08-23 20:07:20
您需要子类UITableViewDiffableDataSource,然后覆盖
func sectionIndexTitles(for tableView: UITableView) 独自一人。
但是,要启用索引的功能,还必须覆盖
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int)下面是我如何实现它的一个例子:
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
}
}发布于 2020-06-11 19:08:35
将self.dataSource插入到UITableViewDiffableDataSource (将自身设置为tableView.dataSource)之后,将tableView.dataSource设置为self,即UITableViewController子类。现在,在您的numberOfSectionsInTableView和numberOfRowsInSection方法中,将这些方法转发到self.dataSource并返回其信息(这是组合模式)。现在,您的UITableViewController只是正常地实现它的节标题,因为它是表的数据源。
我认为,如果已经设置了UITableViewDiffableDataSource,则不应该将自己设置为dataSource,但我想他们设计它的目的是以最容易出错的方式工作,因为在故事板中添加了UITableViewController,默认情况下它被设置为dataSource和delegate。
https://stackoverflow.com/questions/57561664
复制相似问题