我有一个以编程方式创建的 UICollectionView
。创建 Collection View 后,我想根据它必须包含的单元格数量动态定义 Collection View 高度。我不想启用 Collection View 本身的滚动,而是将此 Collection View 作为 subview 添加到包含在垂直 UIScrollView
中的 View 。
例如,如果 UICollectionView
有 10 个 UICollectionViewCells
。它的高度可能为 200.0f,但如果它有 20 个像元,它的高度可能为 300.0f,依此类推。
我已尝试按照 Apple 文档 here 来完成此操作, 重写 collectionViewContentSize
方法。
虽然此方法在调用时返回有效的 CGSize
,但当我实例化 Collection View 时,它的 frame
始终设置为零。
这是我到目前为止所做的:
//subclass UICollectionViewFlowLayout
@interface LabelLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) NSInteger cellCount;
@property (nonatomic) UIEdgeInsets sectionInset;
@property (nonatomic) CGSize itemSize;
@property (nonatomic) CGFloat minimumLineSpacing;
@property (nonatomic) CGFloat minimumInteritemSpacing;
@end
- (id)init
{
self = [super init];
if (self) {
[self setup];
}
return self;
}
-(void)prepareLayout
{
[super prepareLayout];
_cellCount = [[self collectionView] numberOfItemsInSection:0];
}
- (void)setup
{
self.sectionInset = UIEdgeInsetsMake(10.0f, 0.0f, 10.0f, 0.0f);
self.itemSize = CGSizeMake(245.0f, 45.0f);
self.minimumLineSpacing = 10.0f;
self.minimumInteritemSpacing = 20.0f;
}
- (CGSize)collectionViewContentSize
{
CGFloat collectionViewWidth = 550;
CGFloat topMargin = 10;
CGFloat bottomMargin = 10;
CGFloat collectionViewHeight = (self.cellCount * (self.itemSize.height +
self.minimumLineSpacing*2)) + topMargin + bottomMargin;
//THIS RETURNS A VALID, REASONABLE SIZE, but the collection view frame never gets set with it!
return CGSizeMake(collectionViewWidth, collectionViewHeight);
}
//create collectionView in viewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self makeLabels]; //determines the number of cells
LabelLayout *layout = [[LabelLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
self.collectionView.backgroundColor = [UIColor redColor];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
[self.collectionView reloadData];
[self.view addSubview:self.collectionView];
}
此外,当我为 UIcollectionView
显式定义静态框架时,它会按预期创建,因此我知道我唯一的问题是使用 collectionViewContentSize
方法。
所以我的问题是,如何动态设置 UICollectionView
的高度?
最佳答案
Collection View 是 ScrollView ,因此您的-collectionViewContentSize
方法确定内容的大小,而不是整个 View 的大小。您需要设置 Collection View 的 bounds
或 frame
属性来设置 Collection View 本身的大小。
您可能还想将它的 scrollEnabled
属性设置为 NO
。
关于ios - 动态设置 UICollectionView 的 ContentSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17796583/