Instagram / IGListKit

A data-driven UICollectionView framework for building fast and flexible lists.
https://instagram.github.io/IGListKit/
MIT License
12.84k stars 1.54k forks source link

CollectionContext sometimes returns nil for cell in sectionControllerWillEnterWorkingRange #175

Closed yusuftor closed 7 years ago

yusuftor commented 7 years ago

New issue checklist

General information

I'm using the working range delegate to preload both images and generate an attributed string out of text. Inside the delegate function sectionControllerWillEnterWorkingRange, I have the following code:

theSectionModel.retrieveCaption(for: item, font: MediaCell.captionFont) { [weak self] caption in
    if let strongSelf = self,
       let cell = strongSelf.collectionContext?.cellForItem(at: 0, sectionController: strongSelf) as? MediaCell {
           cell.caption.attributedText = caption
       }
    }
}

This successfully retrieves my caption but returns nil for cellForItem(), therefore never setting the attributed text. This is odd because after retrieving the caption, it retrieves the image in a similar fashion but the cellForItem() call succeeds. My working range is set to 2.

You can test the retrieval of a nil cell by adding the following code in the demo project WorkingRangeSectionController under sectionControllerWillEnterWorkingRange:

let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    let cell = self.collectionContext?.cellForItem(at: 1, sectionController: self) as? ImageCell
    print("This cell is: ", cell)
}

This will cause some of the output to say "This cell is: nil". Is this a bug, or is there a reason it does this that I'm not aware of?

P.S. It looks like the website where the images for the WorkingRangeSectionController come from is down.

yusuftor commented 7 years ago

Ok I'm an idiot, sorry.

Just realised that because they're not on screen they're not going to be in the collection context! So if anyone is wondering the solution is to have an "attributedString" parameter that is set when you retrieve the caption. That way, when the cell is loaded on screen by using cellForItem(), it can check to see if the attributedString parameter has been set and then use that value.

I'm gonna close this.

jessesquires commented 7 years ago

Thanks @yusuftor !