UICollectionView使边界更改上的布局无效 [英] UICollectionView Invalidate Layout On Bounds Changes
问题描述
我目前有以下代码片段用于计算 UICollectionViewCells
尺寸:
I currently have the following snippet for calculating UICollectionViewCells
sizes:
- (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
改变大小,那么处理这两个边缘情况并重新计算大小的好方法是什么?
This works. However, I'm now adding a keyboard observer in viewDidLoad
(which is triggering the the delegate and data source methods for the UICollectionView
before it appears and resizes itself from the storyboard). The bounds are thus wrong. I also would like to support rotation. What's a good way of handling these two edge cases and re-calculating the sizes if the UICollectionView
changes size?
推荐答案
当集合视图的边界发生变化时,使布局无效的解决方案是覆盖 shouldInvalidateLayoutForBoundsChange:
并返回是
。
它也在文档中说明: https://developer.apple。 com / documentation / uikit / uicollectionviewlayout / 1617781-shouldinvalidatelayoutforboundsc
The solution for invalidating your layout when the bounds of the collection view changes is to override shouldInvalidateLayoutForBoundsChange:
and return YES
.
It's also stated in the documentation: https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617781-shouldinvalidatelayoutforboundsc
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
return YES;
}
这也应包括轮换支持。如果没有,请实现 viewWillTransitionToSize:withTransitionCoordinator:
This should cover rotation support as well. If it doesn't, implement 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)
{
}];
}
这篇关于UICollectionView使边界更改上的布局无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!