UICollectionViewCell gets hidden randomly

2019-02-18 20:48发布

问题:

I have a UIView in which I am adding a UICollectionView to act as a banner view to look like a carousel. The Viewcontroller in which UIView is present, is part of pageviewcontroller.

PageVC --> UIViewController --> UIView --> UICollectionView.

Each VC has its own banner, so when the page is swiped, I reload the collectionView with the respective data and I am able to see it. Now if visit a page which I already visited, the collectionview cell disappears. The collectionview is visible but the cell is somehow hidden.

The collectionview cell is a customcell and I am not using any custom layout, I am using the default flowlayout. This is working fine in iOS8-devices.

Below is the debugger output, When cell is visible:

CollectionViewCell: 0x7f9db8d9ffa0; baseClass = UICollectionViewCell; frame = (209 3.5; 209 96); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x7f9dbb5dde60>>

When invisible (you can see its hidden now) the dequed cell is now hidden, no clue why it is happening

CollectionViewCell: 0x7f9dbb5897e0; baseClass = UICollectionViewCell; frame = (0 3.5; 209 96); clipsToBounds = YES; hidden = YES; opaque = NO; layer = <CALayer: 0x7f9dbb590220>>

indexPathsForVisibleItems is returning nil.

回答1:

I was calling reloadData from multiple places which caused the system to get confused (may be) especially I have written reloadData in my updateconstraints method and hence for each minor constraint change reloadData was getting called.

Check all places from where you call reloadData for collectionview if you're experiencing the same problem.



回答2:

I've encountered the same problem.

After

  • checking if the UICollectionView reloadData was called in some thread other than the MainThread
  • checking if there is any cases about multi-calling reloadData or updateconstraints

without solving my problem, I realized that in some occasions CGSizeZero was returned for collectionView:layout:sizeForItemAtIndexPath:.

When avoiding the CGSizeZero result, everything works well.



回答3:

Same problem.

Here's my situation:

My collection view has a custom layout. I use the default flow layout without any problem.

When I use my custom layout, whose cell width is a half screen width. When I scroll to the 5th cell, all cells became hidden without reason.

Finally I found out that when I set cell's size correctly in the layout class of the storyboard, the problem is resolved.

Hope this helps.