这是我的 2 美分 - 因为您的商品尺寸是静态的,为什么不在 上设置商品尺寸collectionViewLayout
?
这样做会更快,而不是期望集合视图为每个单元格调用其委托方法。
viewWillLayoutSubviews
可用于检测视图控制器上的旋转。
invalidateLayout
可以在集合视图布局上使用以强制它再次准备布局,导致它在这种情况下以新尺寸定位元素。
- (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()
}