user2507194
user2507194

Reputation: 185

UICollectionView datasource method not called after reload data

I am trying to fetch data from website and add to my collectionview, but the problem when I called [self.collectionView reloadData], it's not working.

So my code is as following:

- (void)viewDidLoad {
    [PYBSkuApi getSKUList:1 andHotId:@"17" success:^(NSArray *skuList) {
        self.dataSource = [NSMutableArray arrayWithArray:skuList];
        [self.skuCollectionView reloadData];
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}


// Data source 

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self.dataSource count];
}

- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 1;
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
....
}

The problem is when I reload the collection view, after the self.dataSource is updated, it goes into

 - (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView

But never goes into

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

I don't know why.

Upvotes: 2

Views: 1563

Answers (2)

Andrew Romanov
Andrew Romanov

Reputation: 5076

I faced with same problem (sometimes an UICollectionView does not call dataSource's methods after reloadData).
An UICollectionView rebuilds list in layoutSubview method, you can know it if you have set breakpoint in some dataSource's method. To force an UICollectionView reload list, you should invalidate the layout of that collection view:

<...>
[self.collectionView reloadData];
[self.collectionView setNeedsLayout];
[self.collectionView layoutIfNeeded];
<...>

Upvotes: 1

edisongz
edisongz

Reputation: 121

Have you ever called setCollectionViewLayout or initWithFrame:collectionViewLayout:

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
[_collectionView setCollectionViewLayout:flowLayout];

or

_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];

Upvotes: 0

Related Questions