kusumoto_teruya
kusumoto_teruya

Reputation: 2475

UICollectionView visibleCells returns nil

Although UICollectionViewCells is displayed, [collectionView visibleCells] returns nil.

- (void)viewDidLoad{
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 320, 568) collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:@"Cell"];
    [self.view addSubview:self.collectionView];

    NSLog(@"%d", [[self.collectionView visibleCells] count]);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    return cell;
}

Do you have any idea?

Upvotes: 0

Views: 2259

Answers (3)

Marwan Alqadi
Marwan Alqadi

Reputation: 855

Try add this:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    collectionView?.collectionViewLayout.invalidateLayout()
}

Upvotes: 0

Paradise
Paradise

Reputation: 578

The issue is caused by reload has not been finished. The solution is : 1. [collectionView reloadData]; 2. **[collectionView layoutIfNeeded]; 3. the get your - > [collectionView visibleCells];

Upvotes: 4

Aravind G S
Aravind G S

Reputation: 392

Try this in your view controller

- (void) viewDidLayoutSubviews {
   NSLog(@"%d", [[self.collectionView visibleCells] count]);
}

Upvotes: 0

Related Questions