【问题标题】:UITableView diffable data sourceUITableView diffable 数据源
【发布时间】:2020-09-20 16:58:52
【问题描述】:

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

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

【问题讨论】:

    标签: swift xcode uitableview diffabledatasource


    【解决方案1】:

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

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

    最后,在您的子类UITableViewDiffableDataSource 中,您需要重写方法tableView(_:titleForHeaderInSection:)。在此方法的实现中,您可以调用snapshot().sectionIdentifiers[section] 来获取节标识符,然后您可以返回相应的节标题。

    【讨论】:

      【解决方案2】:

      official documentation 有一个使用单个部分的示例,因此通过向 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", "")
          }
        }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        • 2021-12-29
        • 2012-06-25
        • 2021-11-06
        • 1970-01-01
        • 2021-07-23
        相关资源
        最近更新 更多