6

So I'm using UICollectionView under AutoLayout-enabled storyboard. I'm trying to set cell size based on collectionView itself and it's based on [collectionView: layout: sizeForItemAtIndexPath:] method. collectionView also depends on auto layout and it gives wrong size at first time (I assume this is before view is layouted). I know they will have correct size after viewDidLayoutSubviews method is called but it causes double reloading of the collectionView items which makes UI glitches at run time.

Here is [collectionView: layout: sizeForItemAtIndexPath:] method of my implementation.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize innerSize = CGSizeMake(galleryView.frame.size.width - 80, galleryView.frame.size.height - 40);
    GLPhotoAsset *photo = [(PCOpticsPhotoPoint *)_cluster.points[indexPath.row] photo];
    CGFloat ratio = MIN(innerSize.width / photo.size.width, innerSize.height / photo.size.height);

    return CGSizeMake(photo.size.width * ratio, photo.size.height * ratio);
}
Pei
  • 11,452
  • 5
  • 41
  • 45
  • "I'm trying to set cell size based on collectionView" Not following you here? – Kyle Truscott Jul 11 '14 at 20:23
  • @KyleTruscott I'm calculating and returning cell size based on collectionView in [collectionView: layout: sizeForItemAtIndexPath:] method. The problem is that this method is called before auto-layout is done. – Pei Jul 12 '14 at 01:55
  • Are you saying that the size of your cells is "related" to the rect of the collection view overall? Perhaps you should post your implementation of `[collectionView: layout: sizeForItemAtIndexPath:]` – Kyle Truscott Jul 12 '14 at 14:39
  • @KyleTruscott I've edited the question to include that method. – Pei Jul 13 '14 at 13:08
  • Thanks, @pei. That makes more sense: you want your cells to be sized in relation to the overall collectionView rect. Are you calling `[galleryView reloadData]` yourself at any point? – Kyle Truscott Jul 13 '14 at 14:20
  • @KyleTruscott Not really. – Pei Jul 13 '14 at 14:50
  • So you do? Where in your code do you call it? You should only call `reloadData` if your data changes later. – Kyle Truscott Jul 13 '14 at 15:00
  • I don't need it. It loads at first time only. – Pei Jul 13 '14 at 15:05

2 Answers2

1

Make sure that your Clip Subviews property of view is Checked . . . .

And your collectionView property cellSize must be proper in Size & Location Section . . .

May be this helps you . . .

iHardikTrivedi
  • 559
  • 3
  • 16
0

As you are getting a wrong layout size before sizeForItemAtIndexPath: is called, then goto storyboard and check the cell size given for these 3 - CollectionView, CollectionViewCell and CollectionViewFlowLayout

Make them same . (also make the size relative to the default collection view size, as u require)

BrianChristo
  • 193
  • 1
  • 14