调整 UICollectionViewCell 的大小以适合图像

Resize UICollectionViewCell to fit image

我想调整 UICollectionViewCell 的大小以适合经过合理调整并保持 dimensions/aspect 比例的图像。如果我只是将单元格的大小设置为图像的大小,它可能太大了。另外,如果我 运行 在不同尺寸的设备上,间距不一致。我必须以编程方式实现 collectionView 才能克服这个问题吗?

我看到很多应用程序都这样做,所以这是一个非常普遍的问题,可能已经作为一个框架得到解决。

示例:

UICollectionView其实是任意布局的。碰巧默认是 UICollectionViewFlowLayout,它是一个网格,但您可以通过实现您自己的 UICollectionViewLayout protocol. Int the case you cited its pretty easy. The width of the cells is the collectionview (width minus the padding) divided by two. The height is the aspect ratio times the width + the spacing + the label height. all the cells with indices divisible by 2 go in the right column and the rest go in the left column. It should be easy to calculate these values for layoutAttributesForItem(at:). Unfortunately its a bit harder to calculate for collectionViewContentSize 实例将其更改为任何内容。假设您的 collectionview 足够小,我认为最好只预先计算所有的高度并将缓存的值用于这些函数。

github上有很多开源的可以参考。

https://github.com/zhangsuya/SYStickHeaderWaterFall