【发布时间】:2020-02-22 09:26:55
【问题描述】:
我正在对UITableViewDiffableDataSource 进行一些修改,我能够毫无问题地加载一个tableView。我正在尝试在 tableView 中创建节标题,但是我遇到了一些不稳定的行为。
section enum enum 定义如下:
enum AlertLevel: String, Codable, CaseIterable {
case green = "green"
case yellow = "yellow"
case orange = "orange"
case red = "red"
}
这是我对tableView(viewForHeaderInSection:)的实现
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = dataSource.snapshot().sectionIdentifiers[section].rawValue.capitalized
label.textColor = UIColor.black
return label
}
这让我在 tableView 顶部的标题单元格中堆叠了 4 个标签。
我将 Dash 启动到 RTFD,我看到 tableView(titleForHeaderInSection:) 是另一种剥猫皮的方法。所以我把它扔进去了:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataSource.snapshot().sectionIdentifiers[section].rawValue.capitalized
}
我扔了一个断点,它永远不会被击中。所以我实现了tableView(heightForHeaderInSection:) 并且标题得到更新,但标题没有显示字符串。
该表的加载速度比使用 IndexPaths 的“老式方式”快很多(我正在使用 USGS 地震数据库来学习 TableViewDiffableDataSource),但我无法显示标题。
有人知道如何让部分在TableViewDiffableDataSource 上工作吗?我很难相信他们会在没有这种基本功能的情况下让这样的东西进入野外,所以我只能得出结论,我正在搞砸一些东西......什么,我不知道 :)
哦...这是我定义数据源的方式:
func makeDataSource() -> UITableViewDiffableDataSource<AlertLevel, Earthquake> {
return UITableViewDiffableDataSource(tableView: tableView) { tableView, indexPath, earthquake in
let cell = tableView.dequeueReusableCell(withIdentifier: self.reuseID, for: indexPath)
cell.textLabel?.text = earthquake.properties.title
cell.detailTextLabel?.text = earthquake.properties.detail
return cell
}
}
【问题讨论】:
-
检查您是否使用了设置节标题的方法中的一种。所以要么使用titleForHeaderInSection,要么使用viewForHeaderInSection,但不要同时使用这两种方法。
-
是的,我尝试了一种方法,但没有成功。其他明显的方式也没有。我想我会成为 Cortes 并用这个“烧毁船只”,然后全力以赴 SwiftUI、Combine 等。
-
heightForHeaderInSection - 是一个委托方法。这就是它被调用的原因。 titleForHeaderInSection 没有被调用,因为它是 UITableViewDataSource 协议的数据源方法。它不起作用,因为您使用的是 DiffableDataSource。你不能同时使用它们。
标签: ios swift uitableview diff diffabledatasource