Display Unexpected layout in UICollectionviewCell when transition

As the attached picture tell so. I have a problem when i use setCollectionViewLayout function for layout’s transition.
From my experiment, I suspected a dequeueReusableCell is reused from old layout. When i keep scroll down. This error cell is still shown .

Are you doing any housekeeping in prepareForReuse? If not, you need to ensure you refresh everything when providing the cell in cellForItemAtIndexPath.

I only set an image to nil. Could you give me an example of refreshing in prepareForReuse method ?

super.prepareForReuse()
self.Thumbnail.image = nil

I figured it out. In collectionView.dequeueReusableCellWithReuseIdentifier, it creates a cell with init(_frame) method. the cell does not know what layout should be displayed. so i just check current cell’s layout against collection view’s layout.
If they are not the same. I just update cell’s layout with new layout including recalculate subviews inside the cell.

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let ProductCardCellpt : ProductCardCell? = collectionView.dequeueReusableCellWithReuseIdentifier("ProductCardCell", forIndexPath: indexPath) as? ProductCardCell
    if ProductCardCellpt?._currentLayout != _CurrentLayoutType  {
        ProductCardCellpt?.setLayout(_CurrentLayoutType)
    }
}

I can see how that would work but I have a feeling it might be more efficient (and would look cleaner) if you always cleared that _currentLayout in prepareForReuse and then you would not need the conditional in cellForItemAtIndexPath.

Avoiding conditional tests used to really matter for fast execution but now we have an embarrassment of power in our devices it may not matter so much. If your preference is to do it this way, OK.

Why do you use the leading _ on the variable names?

I don’t want to update cell’s layout every time the function cellForItemAtIndexPath is called. so i put conditional test there. I am not sure if i update cell’s layout inside the cellForItemAtIndexPath function. Does it cost more power of cpu ? If there is a better way,more elegant,cleaner. please tell me a solution so i can try.

i use prefix _ on variable names for my own convenient to know this variable belong to the self.class. I know it s a little bit ugly. Now i have changed it already and i’ll use prefix _ for private variable.

Thank for your suggestion.

I’m not saying it’s wrong, just different to what I am used to seeing :slight_smile: You certainly have a nice-looking app there, I particularly like the transition from large picture cell to small.