ios - 使用 UITableViewDiffableDataSource 创建章节标题

标签 ios swift uitableview diff diffabledatasource

我正在对 UITableViewDiffableDataSource 进行一些修改,我能够毫无问题地加载 tableView。我正在尝试在 tableView 中创建节标题,但是我遇到了一些古怪的行为。

section 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:) 并更新了 header ,但没有显示 header 的字符串。

该表的加载速度比使用 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
    }
}

最佳答案

我能够通过子类化 UITableViewDiffableDataSource 类来做到这一点,如下所示:

class MyDataSource: UITableViewDiffableDataSource<Section, Int> {

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let section = self.snapshot().sectionIdentifiers[section]
        return section.header
    }
}

你的 Section 在哪里:

enum Section: Int {
    case one

    var header: String {
        switch self {
        case .one: return "Header One"
        }
    }
}

然后以这种方式分配新创建的数据源:

dataSource = MyDataSource<Section, Int>

意思是,您不再需要使用 UITableViewDiffableDataSource,而是使用子类 MyDataSource 类。

关于ios - 使用 UITableViewDiffableDataSource 创建章节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58568472/

相关文章:

ios - 带有 xib 文件和自定义构造函数的自定义 UITableViewCell

ios - 沉默 NewRelic 日志记录到控制台

ios - 检查来自 iOS 设备的 TCP 流量

swift - 如何让 ClockKit 生成超过 100 个时间线条目?

swift - Swift 是否有与 pdb.set_trace() 等效的函数

objective-c - UITableviewController - 更新特定单元格

objective-c - 我找不到这个内存泄漏。我以为我正在正确地释放一切

ios - 如果我有一个过滤搜索结果的 UITableView,如何将 ViewDidLoad() 上的 IndexPath 设置为常量,即使在搜索时也是如此

swift - 无法滚动到 tableView 中某个部分的一行

ios - 从 App-delegate 重新加载或运行函数