首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用UITableViewDiffableDataSource创建节标题

使用UITableViewDiffableDataSource创建节标题
EN

Stack Overflow用户
提问于 2019-10-26 14:04:54
回答 1查看 988关注 0票数 4

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

节枚举的定义如下:

代码语言:javascript
复制
    enum AlertLevel: String, Codable, CaseIterable {
        case green = "green"
        case yellow = "yellow"
        case orange = "orange"
        case red = "red"
    }

这是我对tableView(viewForHeaderInSection:)的实现

代码语言:javascript
复制
    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 to RTFD,我看到tableView(titleForHeaderInSection:)是另一种剥皮的方法。所以我把这个放进去:

代码语言:javascript
复制
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return dataSource.snapshot().sectionIdentifiers[section].rawValue.capitalized
    }

我添加了一个断点,但它永远不会命中。因此,我实现了tableView(heightForHeaderInSection:)并更新了标头,但没有显示标头的字符串。

该表的加载速度比使用IndexPaths的“老式方法”快得多(我正在使用美国地质勘探局地震数据库学习TableViewDiffableDataSource),但我无法显示标题。

有人知道如何让部分在TableViewDiffableDataSource上工作吗?我很难相信他们会在没有这些基本功能的情况下让这样的东西出现,所以我只能得出结论,我搞砸了一些up...what,我不知道:)

Oh...and下面是我定义数据源的方式:

代码语言:javascript
复制
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
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-10-28 05:55:57

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

代码语言:javascript
复制
class MyDataSource: UITableViewDiffableDataSource<Section, Int> {

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

你的Section在哪里:

代码语言:javascript
复制
enum Section: Int {
    case one

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

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

代码语言:javascript
复制
dataSource = MyDataSource<Section, Int>

这意味着,您不再需要使用UITableViewDiffableDataSource,而是使用一个子类MyDataSource类。

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

https://stackoverflow.com/questions/58568472

复制
相关文章

相似问题

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