UICollectionView, simply fit cell to width?

馋奶兔 提交于 2019-11-28 20:11:57
Nikita Took

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.

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.

I my case cell inset making extra shapes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!