UICollectionView's cellForItemAtIndexPath is not being called

后端 未结 30 2249
再見小時候
再見小時候 2020-12-07 11:11

Only my second time using UICollectionView\'s and perhaps I have bitten off more than I can chew but nevertheless:

I am implementing a UICollectionView (myCollection

相关标签:
30条回答
  • 2020-12-07 11:29

    When using UICollectionViewDelegateFlowLayout be careful on what this function returns. Both width and height should be greater than 0. I used window as frame reference but due to complicated view hierarchy window was nil at runtime. If you need adjust the width of the element based on screen width use UIScreen.main.bounds.

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: 
               UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {}
    
    0 讨论(0)
  • 2020-12-07 11:30

    My issue was that I had 2 collection views within the same view, and both were sharing a computed UICollectionViewFlowLayout instance. Once I created separate instances of the same flow layout, it worked fine.

    0 讨论(0)
  • 2020-12-07 11:30

    In my case the collection view was not fully visible in its parent view due to wrong auto layout constraints. So fixing the constraints made the collection view all visible and cellForItemAtIndexPath was called.

    0 讨论(0)
  • 2020-12-07 11:31

    In my case, it was because my layout class incorrectly subclassed from UICollectionViewLayout instead of UICollectionViewFlowLayout

    0 讨论(0)
  • 2020-12-07 11:33

    The cellForItemAtIndexPath will not get called if you do not provide the content size information to collection view.

    1. If you are using Flow layout: You need to set the item sizes properly.
    2. If you have a custom layout subclassed from UICollectionViewLayout: Ensure you are returning a proper size from the collectionViewContentSize method.

    In case of the latter, you will also observe that your layoutAttributesForElementsRect is also not called. The reason is that you have not specified what is your content size and by default the size will be CGSizeZero. This basically tell collection view that you don't have any content to paint so it does not bother asking you for attributes or cells.

    So, just override collectionViewContentSize and provide a proper size there, it should solve your problem.

    0 讨论(0)
  • 2020-12-07 11:34

    I sunk a bit of time with this issue coming op with a CollectionView in a Contained view controller loaded from a storyboard. I ended up just deleting the contained view controller, and recreating it in the storyboard, and this seemed to get rid of the issue. My guess is there was some kind of storyboard corruption that had taken place.

    0 讨论(0)
提交回复
热议问题