【问题标题】:UITableViewDiffableDataSource with different objects具有不同对象的 UITableViewDiffableDataSource
【发布时间】:2020-03-23 02:46:12
【问题描述】:

我目前在使用 UITableViewDiffableDataSource 时遇到问题。

我想尝试一下这个新功能,所以我在网上看了很多教程,但似乎没有一个能回答我的问题。

在我当前的 viewController 中,我有一个 UITableView,有 3 个不同的对象(每个对象都有不同的类型),但 UITableViewDiffableDataSource 被强类型化为一个。

点赞:dataSource = UITableViewDiffableDataSource <SectionType, ItemType>

我的所有部分都包含类似

的内容
func numberOfSections(in tableView: UITableView) -> Int {
    return 3
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {        
        return bigObject.ObjectsOfType1.count
    } else if section == 1 {
        return bigObject.ObjectsOfType2.count
    } else {
        return bigObject.ObjectsOfType3.count
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! CustomTableViewCell
    if indexPath.section == 0 {
        cell.buildWithFirstObject(obj: bigObject.ObjectsOfType1[indexPath.row])
    } else if indexPath.section == 1 {
        cell.buildWithFirstObject(obj: bigObject.ObjectsOfType2[indexPath.row])
    } else {
        cell.buildWithFirstObject(obj: bigObject.ObjecstOfType3[indexPath.row])
    }
}

在我的情况下使用 diffable dataSource 有技巧吗?

任何帮助表示赞赏!感谢您阅读我:)

【问题讨论】:

  • 这段代码遇到了什么麻烦?
  • 使用 diffable 数据源似乎只允许我为一个部分加载数据,因为每个部分的“项目类型”都不同。

标签: ios swift diffabledatasource


【解决方案1】:

对于最简单的方法,使用AnyHashable 作为项目标识符,使用enum 作为部分标识符。已接受答案的问题在于,当您向表中添加功能层时,它会增加繁重的复杂性,因为您必须始终以通用 enum 而不是您的自定义类型开始和结束,并且在您知道它之前有开关到处。这种代码根本不读我们。而且我真的很讨厌看到我的数据源从自定义类型的数组变为相同的泛型数组enum

而且,与其他人所说的相反,您不能将Hashable 用于泛型类型,因为您不能使用协议本身来符合自身,这就是AnyHashable 存在的原因,“类型擦除”替代品。

private enum Section {
    case title
    case kiwi
    case mango
}

private struct Title: Hashable {}

private struct Kiwi: Hashable {
    let identifier = UUID().uuidString
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(identifier)
    }
    
    static func == (lhs: Kiwi, rhs: Kiwi) -> Bool {
        return lhs.identifier == rhs.identifier
    }
}

private struct Mango: Hashable {
    let identifier = UUID().uuidString
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(identifier)
    }
    
    static func == (lhs: Mango, rhs: Mango) -> Bool {
        return lhs.identifier == rhs.identifier
    }
}

var dataSource: UITableViewDiffableDataSource<Section, AnyHashable>!

dataSource = UITableViewDiffableDataSource(tableView: tableView,
                                           cellProvider: { (tableView, indexPath, item) -> UITableViewCell? in
    switch item {
    case is Title:
        return TitleCell()
        
    case let item as Kiwi:
        let cell = tableView.dequeueReusableCell(withIdentifier: someIdentifier,
                                                 for: indexPath) as? SomeCell
        cell?.label.text = item.identifier
        return cell
        
    case let item as Mango:
        let cell = tableView.dequeueReusableCell(withIdentifier: someIdentifier,
                                                 for: indexPath) as? AnotherCell
        cell?.label.text = item.identifier
        return cell
    default:
        return nil
    }
})

var initialSnapshot = NSDiffableDataSourceSnapshot<Section, AnyHashable>()
initialSnapshot.appendSections([.title, .kiwi, .mango])
initialSnapshot.appendItems([Title()], toSection: .title)
initialSnapshot.appendItems([k1, k2, k3], toSection: .kiwi)
initialSnapshot.appendItems([m1, m2, m3], toSection: .mango)
self.dataSource.apply(initialSnapshot, animatingDifferences: false)

【讨论】:

    【解决方案2】:

    另一种可能阻止将NSObject 转换为您期望的任何内容(这可能容易崩溃),是将您的不同对象作为关联值包装在符合Hashableenum 中。然后,在你的出队回调中,你得到枚举,并且可以解开相关的值。所以像

    enum Wrapper: Hashable {
      case one(Type1)
      case two(Type2)
      case three(Type3)
    }
    
    dataSource = UITableViewDiffableDataSource <SectionType, Wrapper>(collectionView: collectionView!) { [weak self] (collectionView: UICollectionView, indexPath: IndexPath, wrapper: Wrapper) -> UICollectionViewCell? in
      switch wrapper {
        case .one(let object):
          guard let cell = dequeueReusableCell( ... ) as? YourCellType else { fatalError() }
          // configure the cell
          cell.prop1 = object.prop1
          return cell
    
        case .two(let object2):
          guard let cell = dequeueReusableCell( ... ) as? YourCellType2 else { fatalError() }
          // configure the cell
          cell.prop1 = object2.prop1
          return cell
    
        case .three(let object3):
          guard let cell = dequeueReusableCell( ... ) as? YourCellType3 else { fatalError() }
          // configure the cell
          cell.prop1 = object3.prop1
          return cell
      }
    }
    

    你甚至可以用一个 return 来简化它。

    【讨论】:

    • 这个不错!我会试试看 !现在我所做的就是让我的不同对象继承自 NSObject。
    • 我也遇到了与 OP 相同的问题,这非常有帮助!但是我很难正确设置我的快照。您将如何为您提供的示例设置 NSDiffableDataSourceSnapshot?我不知道如何让它使用 2 种不同的数据类型(其中一种是数组,另一种不是)。
    • @dank_muffin 这取决于您如何构建数据以及如何呈现数据。你可以做类似Swift let newSnapshot = NSDiffableDataSourceSnapshot&lt;Section, Wrapper&gt;() newSnapshot.appendSections([Section.first, Section.last]) newSnapshot.appendItems(allItems.filter { $0 == .one}, toSection: .first) newSnapshot.appendItems(allItems.filter { $0 == .three}, toSection: .last)
    • @oflannabhra 感谢您发布此解决方案,但是当关联的值是像 case three([Type3]) 这样的数组时,我很挣扎。我应该如何将它附加到快照中以应用?如果我这样做 snapShot.appendItems(wrapper3, toSection: section) 它只会将一个元素附加到该部分
    • 如果您使用的是数组,则需要在调用appendItems() 之前处理合并数组。如果您将数组传递给该函数,它会将 整个数组 添加为单独的项目。我建议您重新考虑如何存储数据。
    【解决方案3】:

    似乎使用 UITableViewDiffableDataSource&lt;Section, NSObject&gt; 并让我的不同对象继承自 NSObject 工作正常。

    【讨论】:

    • 你可以使用泛型来代替NSObject。
    • 或者只是 Hashable
    猜你喜欢
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2015-06-22
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多