在不同的设备方向上更改 UICollectionViewCell 大小 [英] Change UICollectionViewCell size on different device orientations

查看:25
本文介绍了在不同的设备方向上更改 UICollectionViewCell 大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 UICollectionViewFlowLayoutUICollectionView.

I am using an UICollectionView with UICollectionViewFlowLayout.

我通过设置每个单元格的大小

I set the size of each cell through the

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:completion: 将使布局无效并使用动画调整单元格的大小(如果您没有额外的调整要执行,您可以将 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆