Search code examples
iosinitializationuicollectionviewuicollectionviewcellreusability

Check if UICollectionViewCell already created to avoid reuse


I'll make it short.

Situation

Let say i have 5 cells, im doing some kind of "method" on UIView who's placed inside the cell(as a subview). I need this "method" to occur only once(when the cell initialize),and avoid this "method" from happening again over the cellForItemAtIndexPath.

What i have tried

  • In the UICollectionViewCell subclass, declare bool value var alreadyCreated = false and check inside the cellForItemAtIndexPath if the propery is False - meaning it havent created yet. and than run the "method" and change the propert to True. Problem - beacuse of the reuse even for cells that havent created yet, it set the property alreadyCreated to true.

Any suggestions how to determine if the cell is already been created even when reusing cells?

Thanks guys!


Solution

  • Okay, I finally understood what the question is!

    This is actually really easy, because the list that keeps track of this already exists. It's the data model.

    So, in cellForRowAtIndexPath:, you are looking into the data model for this section/row and using that info to populate the cell.

    Well, in that data model, you also need to have a Bool value that starts out false, and (in cellForRow) if it's false you switch it to true and do your one-time configuration. In that way, you end up doing this task exactly once for each apparent row of the table.

    Really this is exactly the same as when I populate cells with images that need to be downloaded from the Internet. How do I know whether I've downloaded the image for this row? Because the image is right there in the model! If it's not there, I know I need to start downloading it. If it is there, I've done this work already and I just supply the image. Thus the image for every row is downloaded a maximum of once.