如何在旋转时定义CollectionView的大小 [英] How do I define the size of a CollectionView on rotate

查看:195
本文介绍了如何在旋转时定义CollectionView的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有2个CollectionView控制器的viewcontroller。

I have a viewcontroller with 2 CollectionView Controllers.

我希望轮换时只有一个集合视图调整为自定义大小而另一个保持不变。

I would like on rotation that only one of the collection views resize to a custom size while the other remains the same.

我试过使用:

- (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);
}

然而,这只会改变两个集合视图。如何让它仅限于一个系列?

However that just changes both collectionviews. How do I get it to be specific to only one collection?

推荐答案

继承我的2美分 - 因为你的商品尺寸是静态的你不在 collectionViewLayout 上设置项目大小吗?

Heres my 2 cents - because your item sizes are static why don't you set the item size on the collectionViewLayout?

这样做比预期更快集合视图为每个单元格调用其委托方法。

It will be quicker to do this rather than expecting the collection view to call its delegate method for every cell.

viewWillLayoutSubviews 可用于检测视图上的旋转控制器。
invalidateLayout 可用于集合视图布局,以强制它再次准备布局,使其在这种情况下使用新大小定位元素。

viewWillLayoutSubviews can be used for detection of rotation on view controllers. invalidateLayout can be used on a collection view layout to force it to prepare the layout again causing it to position the elements with the new sizes in this case.

- (void)viewWillLayoutSubviews;
{
    [super viewWillLayoutSubviews];
    UICollectionViewFlowLayout *flowLayout = (id)self.firstCollectionView.collectionViewLayout;

    if (UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication.statusBarOrientation)) {
        flowLayout.itemSize = CGSizeMake(170.f, 170.f);
    } else {
        flowLayout.itemSize = CGSizeMake(192.f, 192.f);
    }

    [flowLayout invalidateLayout]; //force the elements to get laid out again with the new size
}

编辑:使用Swift2.0更新示例

override func viewWillLayoutSubviews() {
  super.viewWillLayoutSubviews()

  guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
    return
  }

  if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
    flowLayout.itemSize = CGSize(width: 170, height: 170)
  } else {
    flowLayout.itemSize = CGSize(width: 192, height: 192)
  }

  flowLayout.invalidateLayout()
}

这篇关于如何在旋转时定义CollectionView的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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