我目前有以下代码片段来计算UICollectionViewCells大小:
- (CGSize)collectionView:(UICollectionView *)mainCollectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeforItemAtIndexPath:(NSIndexPath *)atIndexPath { CGSize bounds = mainCollectionView.bounds.size; bounds.height /= 4; bounds.width /= 4; return bounds; }
这个工作.然而,我现在在viewDidLoad中添加一个键盘观察器(它触发了UICollectionView的委托和数据源方法,然后再出现,并从故事板中调整大小).这样的界限是错误的.我也想支持轮换.如果UICollectionView改变大小,那么处理这两个边缘情况并重新计算大小的好方法是什么?
解决方法
当集合视图的边界更改时,无效布局的解决方案是覆盖shouldInvalidateLayoutForBoundsChange:并返回YES.
在文档中也有说明: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UICollectionViewLayout_class/index.html#//apple_ref/occ/instm/UICollectionViewLayout/shouldInvalidateLayoutForBoundsChange:
在文档中也有说明: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UICollectionViewLayout_class/index.html#//apple_ref/occ/instm/UICollectionViewLayout/shouldInvalidateLayoutForBoundsChange:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds { return YES; }
这也应该涵盖旋转支持.如果没有,实现viewWillTransitionToSize:withTransitionCoordinator:
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [coordinator animatealongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) { [self.collectionView.collectionViewLayout invalidateLayout]; } completion:^(id<UIViewControllerTransitionCoordinatorContext> context) { }]; }