[英]UICollectionViewCell sized relative to its collection-view
I have a (horizontal) collection-view, and I change its size via auto layout constraints. 我有一个(水平)集合视图,并且通过自动布局约束来更改其大小。 However, when the collection-view's size changes, the cell remains the same static size.
但是,当集合视图的大小更改时,单元格将保持相同的静态大小。
To demonstrate, here's the collection-view in the view debugger (I've labeled both the collectionview and one of its cells): 为了演示,这是视图调试器中的collection-view(我已经标记了collectionview及其单元格之一):
As you can see, the cell remains the original size and is now actually taller than its encasing collection-view. 如您所见,单元格保持原始大小,现在实际上比其包围的收集视图高。
So how can I constrain the cell to always fit within its collection-view? 那么,如何限制单元格始终适合其收藏视图呢?
If you want to resize your view you can use the following to reset the item size on rotation, this would go inside your view controller subclass. 如果要调整视图的大小,则可以使用以下命令在旋转时重置项目大小,这将放入视图控制器子类中。
This should be fairly efficent as it is only called when the size of the visible view controller changes. 这应该是相当有效的,因为只有在可见视图控制器的大小更改时才调用它。
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator;
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:({
^(id<UIViewControllerTransitionCoordinatorContext> context) {
UICollectionViewFlowLayout *layout = (id)self.collectionView.collectionViewLayout; {
CGFloat height = CGRectGetHeight(self.collectionView.bounds);
layout.itemSize = (CGSize) {
.width = height,
.height = height
};
}
[layout invalidateLayout];
};
}) completion:nil];
}
You should also check out these answers for some more solutions. 您还应该查看这些答案以获得更多解决方案。
I solved this through setting the item's height and width equal to the collection-view's height. 我通过将项目的高度和宽度设置为等于集合视图的高度来解决此问题。 I do this in sizeForItemAtIndexPath:
我在sizeForItemAtIndexPath中执行此操作:
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(collectionView.frame.size.height, collectionView.frame.size.height);
}
Because in my case the cell's need to be perfect squares, setting the cell's height and width to the height of the collection-view works perfectly. 因为在我的情况下,单元需要是完美的正方形,所以将单元的高度和宽度设置为集合视图的高度是完美的。
Not that your class must implement the UICollectionViewDelegateFlowLayout protocol for this method to be exposed. 并不是您的类必须实现UICollectionViewDelegateFlowLayout协议才能公开此方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.