cellForItemAtIndexPath not called but numberOfItem

2019-02-02 19:53发布

This could be a duplicate post but I haven't found the solution in any of this:

enter image description here

I'm setting my UICollectionView as:

UINib *nib = [UINib nibWithNibName:@"CollectionViewCell"
                           bundle:[NSBundle mainBundle]];
[_collectionView registerNib: nib forCellWithReuseIdentifier:@"bCell"];

(I've tried to set delegate, without delegate, etcetera).

But then, only the

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section gets called while

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath doesn't.

I've checked the numberOfItemsInSection I return, and it's always > 0 (it's exactly 17).

I've checked to call [_collectionView reloadData]; and nothing happens either.

I've tried different things but I can't make it work.

Furthermore, my UICollectionView should be here but it's not:

enter image description here

Does anyone have a clue? Thank you.

12条回答
We Are One
2楼-- · 2019-02-02 20:20

For me the issue was that I was creating my Collection View programmatically but I had given it CGRectZero as its frame. I was laying it out using Auto Layout after viewDidLoad. If I lay out the collection view while the view controller is loading, it ends up calling cellForItemAtIndexPath: correctly.

查看更多
该账号已被封号
3楼-- · 2019-02-02 20:22

Add this to viewDidLoad:

self.automaticallyAdjustsScrollViewInsets = NO;
查看更多
仙女界的扛把子
4楼-- · 2019-02-02 20:22

What helped me was to set the correct itemSize. My cellForItemAtIndexPath was not being called because of the wrong height.

So I set the size at:

[self.myCollectionViewFlowLayout setItemSize:CGSizeMake(170, 300)];
查看更多
孤傲高冷的网名
5楼-- · 2019-02-02 20:27

I also face same issue and finally got to know that i have passed wrong class object for collectionViewLayout , i change to UICollectionViewFlowLayout instead of UICollectionViewLayout while creating object for UICollectionView like below its stared calling all delegate method.

 collectionView = UICollectionView(frame: CGRectMake(5, 0, 400, 40) , collectionViewLayout: UICollectionViewFlowLayout())
查看更多
Melony?
6楼-- · 2019-02-02 20:29

I meet this problem too. I checked all the possible issues, everything looks ok. Then I tried to changed the reload methods.

[self.colView reloadData] -> [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:x]];

Then all things worked. However I still don't understand how.

查看更多
Emotional °昔
7楼-- · 2019-02-02 20:33

I had faced a similar problem. The issue was with the numberOfItems in section. Your cellForRowAtIndexPath might not be called if either your number of sections or number of rows in section is below zero.

查看更多
登录 后发表回答