Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView visibleCells returns 0 before scrolling

I have a UICollectionView that I implement the lazy loading,

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
      [self loadImagesToVisiableCells];
}

It works good. However, the problem is before any scroll, the first a few cells show the placeholder images. So I try to call loadImagesToVisiableCells on my callback of retrieving the json file to be displayed in the UICollectionView below,

- (void)handleReceivedData: (NSArray*)results returnArrayOrDic:(NSNumber *)returnArrayOrDic{
    NSLog(@"***************************");
    NSLog(@"handleReceivedData has been called from PromotionViewController");
    NSLog(@"jsonArray Length:%d",[results count]);
    NSLog(@"jreturnArrayOrDic:%@",returnArrayOrDic);
    if([returnArrayOrDic boolValue] == YES){
      for(NSDictionary *dealDic in results) {
        NSLog(@"dealDic: %@", dealDic);
        //to populate the dealArray
        Deal *deal = [[Deal alloc] initWithDict:dealDic];
        [dealArray addObject:deal];
      }
      NSLog(@"%d deals have been populated to dealArray",[dealArray count]);
    }else{
      NSDictionary *jsonDictionary = (NSDictionary *)results;
      for(id key in jsonDictionary) {

        id value = [jsonDictionary objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
      }
    }
    [self.collectionView reloadData];
    [self loadImagesToVisiableCells];
}

Debug message shows before any scroll, [[collectionView visibleCells] count] returns 0.

    - (void)loadImagesToVisiableCells{
        NSLog(@"starting loadImagesToVisiableCells, visibleCells:%d",[[collectionView visibleCells] count]);
....
}

Any idea?

Regards Hammer

like image 479
Hammer Avatar asked Sep 26 '14 08:09

Hammer


1 Answers

Thanks to Reloading a UICollectionView using reloadData method returns immediately before reloading data

The issue is caused by reload has not been finished. The solution is ,

[collectionView reloadData];
**[self.collectionView layoutIfNeeded];**
[self loadImagesToVisiableCells];
like image 139
Hammer Avatar answered Nov 20 '22 06:11

Hammer