Full Decent Full Decent - 4 months ago 13x
iOS Question

Make UICollectionViewCell exactly fit available space

My cells are squares and look good at any size. I am looking to find the largest size for cells so that displaying all of them will not require scrolling.

And by example, this screen shot is great for 3 players, but kicking it up to 12 players makes them scroll out of bounds, which is to be avoided.

Is there a way to accomplish this?

enter image description here


Based on rdelmar's code above with all the finesse taken out. Brute force calculation ensure the correct answer in some edge cases the other answer fails at.

#define PLAYERS 4.0
#import "ViewController.h"

@interface ViewController ()
@property (weak,nonatomic) IBOutlet UICollectionView *collectionView;

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout setMinimumInteritemSpacing:10];
    [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout setMinimumLineSpacing:10];

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.view setNeedsLayout];

-(void)viewDidLayoutSubviews {
    NSInteger cellMaxSide = 0, rows=9999, cols=9999;
    do {
        // if your cellWidth != cellHeight, switch here to set the larger then smaller of the two
        cols = floorf((self.playerPhotoCollectionView.frame.size.width+10)/((cellMaxSide+1)+10));
        rows = floorf((self.playerPhotoCollectionView.frame.size.height+10)/((cellMaxSide+1)+10));
    } while ((rows * cols >= PLAYERS) && ++cellMaxSide);
    [(UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout setItemSize:CGSizeMake(cellMaxSide,cellMaxSide)];
    [self.collectionView reloadData];

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

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