在不同的设备方向上更改UICollectionViewCell大小 [英] Change UICollectionViewCell size on different device orientations
问题描述
我使用 UICollectionView
与 UICollectionViewFlowLayout
。
我通过
collectionView:layout:sizeForItemAtIndexPath:
当从纵向切换到横向时,我想调整每个单元格的大小以完全适合CollectionView的大小,而不留下填充空间在单元格之间。
When switching from portrait to landscape, I would like to adjust the size of each cell to completely fit the size of the CollectionView, without leaving padding space between cells.
问题:
1)如何在轮换事件后更改单元格的大小?
1) How to change the size of a cell after a rotation event?
2)而且,更好的是,如何使单元格总是适合整个屏幕大小的布局?
2) And, even better, how to make the layout where the cells always fit the entire size of the screen?
推荐答案
1)您可以维护和交换多个布局对象,但有一种更简单的方法。只需将以下内容添加到 UICollectionViewController
子类中,并根据需要调整大小:
1) You could maintain and swap out multiple layout objects, but there's a simpler way. Just add the following to your UICollectionViewController
subclass and adjust the sizes as required:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
// Adjust cell size for orientation
if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
return CGSizeMake(170.f, 170.f);
}
return CGSizeMake(192.f, 192.f);
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self.collectionView performBatchUpdates:nil completion:nil];
}
调用 -performBatchUpdates:完成:
将使布局无效并使用动画调整单元格的大小(如果没有额外的调整,则可以将nil传递给两个块参数)。
Calling -performBatchUpdates:completion:
will invalidate the layout and resize the cells with animation (you can just pass nil to both block params if you've no extra adjustments to perform).
2 )而不是在 -collectionView:layout:sizeForItemAtIndexPath
中对项目大小进行硬编码,只需将collectionView的边界的高度或宽度除以您想要适合屏幕的单元格数。如果您的collectionView水平滚动,则使用高度;如果它垂直滚动,则使用宽度。
2) Instead of hardcoding the item sizes in -collectionView:layout:sizeForItemAtIndexPath
, just divide the height or width of the collectionView's bounds by the number of cells you want to fit on screen. Use the height if your collectionView scrolls horizontally or the width if it scrolls vertically.
这篇关于在不同的设备方向上更改UICollectionViewCell大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!