Search code examples
iosobjective-cuicollectionviewxibuicollectionviewcell

How to change UICollectionViewCell size programmatically (with Xib)


I created a custom subclass of UICollectionViewCell along with a Xib which defines a size for the cell (60 pts by 60 pts).

I also implemented the following:

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = [MainScreen screen];
    CGFloat width = size.width;
    CGFloat item = (width*60)/320;
    return CGSizeMake(item, item);
}

The issue I'm running into is that every time I run my program, the cells in my UICollectionView controller always appear as 60x60 cells. Furthermore, I've been testing on an iPhone 6s which is 375x667 points (so, doing the math, the cells should be ~70x70 not 60x60).

How do I programmatically change the size of the cell (or, rather, override the predefined Xib size)?


Solution

  • This was just inexperience showing on my end. sizeForItemAtIndexPath: was working properly, however the actual frame of the cell image needed to be redefined based on the item parameters. So if I hard coded CGSizeMake(100,100) for the size of my collection view cell, I needed to also resize the image frame that would occupy the cell to 100x100.