Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the same object in two different sections of UICollectionViewCompositionalLayout / UICollectionViewDiffableDataSource

I have a UICollectionView where I lay out two sections (one horizontally scrolling, one vertically scrolling), using UICollectionViewCompositionalLayout. I've combined this with usage of UICollectionViewDiffableDataSource in order to cut down on inconsistencies. However, I've run into a dilemma.

The two sections don't necessarily share the same cell objects, but sometimes there will be a cell in each section that is based off the same object (as each section provides a different context to the object in question). UICollectionViewDiffableDataSource requires every object in the collection to have some sort of unique identifier, and apparently this identifier cannot be shared across sections. Is there a way that I can create a cell in each section based off the same object?

like image 931
Avery Vine Avatar asked Dec 22 '25 16:12

Avery Vine


1 Answers

I ran into the same issue recently. My solution was to wrap the data objects in an Item struct and calculate the identifier by combing the hashes of the section and item.

/// A data source section.
struct Section: Hashable {
    let title: String
    let id: Int

    func hash(into hasher: inout Hasher) {
        hasher.combine(self.id)
    }
}

/// A data source item.
struct Item: Hashable {
    let section: Section
    let object: MyObject

    func hash(into hasher: inout Hasher) {
        hasher.combine(self.section)
        hasher.combine(self.object)
    }
}
like image 87
conmulligan Avatar answered Dec 24 '25 10:12

conmulligan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!