我无法得到这样的布局:
我只能在'sizeForItemAt'方法中设置单元格的大小时实现这一点:
我尝试了苹果的解决方案,比如UICollectionViewCompositionalLayout和UICollectionViewLayout的子类化。但是第一个解决方案不能给予设备旋转所需的灵活性,因为你必须设置组中子项的精确计数。UICollectionViewCompositionalLayout的另一个问题是滚动时间计算-它在屏幕显示后不能给出完整的布局。UICollectionViewLayout的子类化(https://developer.apple.com/documentation/uikit/views_and_controls/collection_views/layouts/customizing_collection_view_layouts)的性能很糟糕。
但即使有上述方法的所有缺点,我也没有得到我需要的确切布局。我可以想象,我们可以使用一种包含四个单元格的额外类型的单元格,但它也不灵活。
我将感激任何帮助。
1条答案
按热度按时间wztqucjr1#
这个布局可以用一个定制的
UICollectionViewLayout
来完成,而且可能比看起来要简单得多。首先,将布局想象成每个部分的网格...... 4列x n 行:
因为我们使用的是正方形,所以第一个项目将占用2列和2行。
为了避免宽度/高度混淆和重复,我们将2x2项称为“Primary”项,1x 1项称为“Secondary”项。
因此,当我们计算布局矩形时,我们可以说:
这很好用,在iPhone 14 Pro Max上给我们这个:
但这并不那么简单,因为当我们旋转手机时,我们不希望这样:
如果我们用的是iPad,我们肯定不想要这个:
所以,我们需要决定我们可以为这个布局做多宽。
当前的电话范围从275到430点宽(纵向方向),所以我们可以说:
如果我们决定Primary item为200 x200,则布局代码的初始部分将更改为:
现在,如果我们的布局看起来像这样(同样,iPhone 14 Pro Max):
旋转电话给我们这个:
iPad看起来是这样的:
我们可能仍然需要一些条件计算...... iPhone SE上的相同代码看起来像这样:
因此,200 x200的主大小对于该设备来说可能太大。
此外,如您所见,设置显式主项目大小不会完全填充宽度。横向方向的iPhone SE的视图宽度为667。如果次要大小(列宽)为100,则6列可以获得600点,最后留下667点的空白空间。
如果这是可以接受的,很好,更少的工作:)否则,我们可以做一个“最佳拟合”计算,要么“增加”一点大小来填充它,要么“缩小”一点大小并扩展到7列。
而且...如果你想要节间距和/或标题,那也需要考虑进去。
这里有一些示例代码来实现这一点: