Iglistkit: Nested adapter collection view sizing

Created on 8 Feb 2018  路  2Comments  路  Source: Instagram/IGListKit

I have an issue very similar to #332. I have a collection view inside a cell and I need to find the height of the collection view content in order to size my cell. This is a chicken and egg problem where I need the size of the content to size the collection view, but that doesn't seem to happen until the collection view has been sized. Is this solvable?

question

Most helpful comment

Ah solved it! For anyone interested, it was solved by reloading the context in a batch update in the ListAdapterDataSource like this:

func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {        
    let sectionController = MySectionController()
    collectionContext?.performBatch(animated: true, updates: { context in
        context.reload(self)
    })
    return sectionController
}

Setting the collection view layout like this:

private let layout = ListCollectionViewLayout(stickyHeaders: false, topContentInset: 0, stretchToEdge: false)

// Set this in cellForItem:
cell.collectionView.collectionViewLayout = layout

And finally retrieving the size of the collection view like this:

override func sizeForItem(at index: Int) -> CGSize {
    guard let width = collectionContext?.containerSize.width else { return .zero }
    return CGSize(width: width, height: layout.collectionViewContentSize.height)
}

All 2 comments

Ah solved it! For anyone interested, it was solved by reloading the context in a batch update in the ListAdapterDataSource like this:

func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {        
    let sectionController = MySectionController()
    collectionContext?.performBatch(animated: true, updates: { context in
        context.reload(self)
    })
    return sectionController
}

Setting the collection view layout like this:

private let layout = ListCollectionViewLayout(stickyHeaders: false, topContentInset: 0, stretchToEdge: false)

// Set this in cellForItem:
cell.collectionView.collectionViewLayout = layout

And finally retrieving the size of the collection view like this:

override func sizeForItem(at index: Int) -> CGSize {
    guard let width = collectionContext?.containerSize.width else { return .zero }
    return CGSize(width: width, height: layout.collectionViewContentSize.height)
}

thank you for your lovely solution it works perfectly if the collection is scrolling vertically but when I change scroll direction to horizontal the app crashed with this error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Height of item 0 in section 0 (300 pt) must be less than or equal to container (0 pt) accounting for section insets {0, 0, 0, 0}'

Was this page helpful?
0 / 5 - 0 ratings