如何使UICollectionViewFlowLayout itemSize动态适合屏幕大小 [英] How to make UICollectionViewFlowLayout itemSize dynamic for screen size
问题描述
我正在以编程方式工作(没有情节提要),并且无法针对不同的屏幕尺寸动态设置layout.itemSize.我收到此错误消息:
I am working programmatically (no storyboard) and am having trouble making layout.itemSize dynamic for different screen sizes. I get this error message:
"UICollectionView必须使用非空布局参数初始化"
"UICollectionView must be initialised with a non-nil layout parameter"
在我的实现文件中包含以下代码:
with the following code in my implementation file:
- (instancetype)init
{
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
CGSize size = self.collectionView.bounds.size;
layout.itemSize = CGSizeMake(size.width, size.height);
[layout setScrollDirection:UICollectionViewScrollDirectionVertical];
layout.minimumLineSpacing = 100.0;
layout.headerReferenceSize = CGSizeMake(0.0, 50.0);
return (self = [super initWithCollectionViewLayout:layout]);
}
例如,对于 layout.itemSize
使用"100,100",我不会收到错误消息.有办法使它动态吗?
I don't get the error message if I use "100,100" for example for layout.itemSize
. Is there a way to make it dynamic though?
我是Objective-C的新手,所以很感谢我对我做错的事情的帮助.
I am new to Objective-C so would appreciate any help on what I am doing incorrectly.
推荐答案
需要使用流委托方法:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize cellSize = CGSizeMake(width, height);
return cellSize;
}
您可以将宽度和高度浮点值指定为所需的任何值.
You specify the width and height float values to whatever you want.
例如,假设您的CollectionView是垂直的,并且您想要一个短的页眉视图,一个大的中间视图和一个小的页脚视图,那么您可以执行以下操作:
For example, lets say your CollectionView is vertical and you want a short header view, a big middle view and a small footer view, then you could do something like:
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize cellSize;
cellSize.width = self.view.bounds.size.width;
if(indexPath.row == 0)
{
// header view height
cellSize.height = 100;
}
else if(indexPath.row == 1)
{
// body view height
cellSize.height = 500;
}
else
{
// assuming number of items is 3, then footer view is last view
// footer view height
cellSize.height = 100;
}
return cellSize;
}
这篇关于如何使UICollectionViewFlowLayout itemSize动态适合屏幕大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!