AKDave
AKDave

Reputation: 1

Is it possible to detect tap on root item of CollectionView using an NSDiffableDataSourceSectionSnapshot

The following code displays some data in a collectionView in a hierarchical display

class PrimaryCollectionViewController: UICollectionViewController {

enum Section: CaseIterable {
    case Main
}

struct Item: Hashable { var mainText: String var type: String }

var dataSource: UICollectionViewDiffableDataSource<Section, Item>! = nil

var listConfiguration = UICollectionLayoutListConfiguration(appearance: .sidebar) let layout = UICollectionViewCompositionalLayout.list(using: listConfiguration) self.collectionView.collectionViewLayout = layout

   let containerCellRegistration =    UICollectionView.CellRegistration<UICollectionViewListCell, Item> { (cell, indexPath, item) in
       var contentConfiguration = cell.defaultContentConfiguration()
       contentConfiguration.text = item.mainText
       cell.contentConfiguration = contentConfiguration
       let disclosureOptions = UICellAccessory.OutlineDisclosureOptions(style: .header)
       cell.accessories = [.outlineDisclosure(options:disclosureOptions)]
   }
    let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in
        var contentConfiguration = cell.defaultContentConfiguration()
        contentConfiguration.text = item.mainText
        cell.contentConfiguration = contentConfiguration
    }
    dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: self.collectionView) {
        (collectionView: UICollectionView, indexPath: IndexPath, item: Item) -> UICollectionViewCell? in

        if item.type == "child" {
            return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: item)
        } else {
            return collectionView.dequeueConfiguredReusableCell(using: containerCellRegistration, for: indexPath, item: item)
        }
    }

    var snapShot = NSDiffableDataSourceSectionSnapshot<Item>()
    let rootItem = Item(mainText: "Root item", type: "parent")
    snapShot.append([rootItem]
    let childItem = Item(mainText: "Child item", type: "child")
    snapShot.append([childItem], to: rootItem)
}

override func collectionView(_ collectionView
                             : UICollectionView, didSelectItemAt indexPath
                             : IndexPath) {
guard let selectedItem = self.dataSource.itemIdentifier(for: indexPath) else {
    return
}
print("Item = \(String(describing: self.dataSource.itemIdentifier(for: IndexPath(indexes: indexPath))))")
}

}

When the root item is selected the list is expanded to show the child item. And when the child item is selected "didSelectItemAt" is called.

My question is, is it possible to detect when the root item is selected?

Thanks in advance.

Upvotes: 0

Views: 45

Answers (0)

Related Questions