Joe Blow Joe Blow - 1 year ago 126
iOS Question

UICollectionView, simply fit cell to width?

Here's a simple UICollectionView in yellow

enter image description here

The red arrow sets the width of the cell. (TBC: clicking on the pink cell: for 'size' select 'Default', then what you set at the red arrow becomes the size of the cell.)

Example, for an upright iPhone set width to 320.

But this seems crazy ... surely I can set the cell width based on the width of the UICollectionView?

There's no problem autosizing the view itself ..

enter image description here

That works fine.

But it seems crazy that I can't set the width of the CELL to be "same as the view". It seems hard to believe one has to set it manually, in code?

TBC In other words, as Nikita points out,

-(CGSize) collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
return self.view.frame.size;

(indeed you also typically need this ...)

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
return UIEdgeInsetsMake(0,0,0,0); //t,l,b,r

In fact - you have to do that in code?! There's no way to do that in Storyboard, with autolayout, or anything else?!

Answer Source

I think you need to take a look at

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

of UICollectionViewLayout where you can set size based on orientation and current frame.

It would indeed seem that you simply have to do this in code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download