UICollectionView, simply fit cell to width?

2019-01-22 17:41发布

问题:

Here's a simple UICollectionView in yellow

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 ..

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
   layout:(UICollectionViewLayout*)collectionViewLayout
   insetForSectionAtIndex:(NSInteger)section
    {
    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?!

回答1:

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.



回答2:

There is a simple way to do this. Here is the swift code. Assumes you want one item wide and in the example my cells are 64 pts high, and I want 8 pts for side margins, and finally collectionView is the name of your UICollectionView.

Insert this into viewDidLoad :

    let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = CGSize.init(width: (UIScreen.main.bounds.width - 16), height: 64.0)

This will set all the cells to default to that size. You can still override individual cells if you subclass UICollectionViewLayout or UICollectionViewFlowLayout, as mentioned in other answers. But if you simply want to have more table view like behavior this should work.



回答3:

I my case cell inset making extra shapes