0

如何使用 Diffable DataSource 在 Tableview 中创建多个部分。?

我使用 Diffable DataSource 创建 Simple TableView 但我无法理解如何使用标题设置多个部分。?

4

2 回答 2

1

首先,您需要通过调用其appendSections(_:)方法将您的部分添加到您的快照中。

然后,您使用 将项目添加到您的部分appendItems(_:toSection:)

最后,在您的子类中UITableViewDiffableDataSource,您需要覆盖方法tableView(_:titleForHeaderInSection:)。在此方法的实现中,您可以调用snapshot().sectionIdentifiers[section]以获取部分标识符,然后您可以返回该部分的适当标题。

于 2020-09-20T18:50:56.893 回答
1

官方文档有一个使用单个部分的示例,因此通过向您提供第二个参数,您appendItems可以定位哪个部分应该填充给定的项目,即:

enum MySectionType {
   case fruits
   case beverage
}

// Create a snapshot
var snapshot = NSDiffableDataSourceSnapshot<MySectionType, String>()        

// Populate the snapshot
snapshot.appendSections([.fruits, .beverage])
snapshot.appendItems(["", ""], toSection: .fruits)
snapshot.appendItems(["coke", "pepsi"], toSection: .beverage)

// Apply the snapshot
dataSource.apply(snapshot, animatingDifferences: true)

如果您想提供部分标题,我将继承UITableViewDiffableDataSource并覆盖相关方法,即:

class MyDataSource: UITableViewDiffableDataSource<MySectionType> {

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

    switch sectionIdentifier {
      case .fruits:
        return NSLocalizedString("Fruits", "")
      case .beverage:
        return NSLocalizedString("Beverage", "")
    }
  }

}
于 2020-09-20T18:53:15.257 回答