动态设置UICollectionView的ContentSize

jac*_*300 11 objective-c ios uicollectionview

我有一个UICollectionView以编程方式创建的.创建集合视图后,我想根据它必须保存的单元格数动态定义集合视图高度.我不想启用滚动集合视图本身,而是将此集合视图作为子视图添加到包含在垂直内部的视图中UIScrollView.

例如,如果UICollectionView有10 UICollectionViewCells.它可能有200.0f的高度,但如果它有20个单元格,它的高度可能为300.0f,依此类推.

我试图通过遵循此处的Apple文档来实现此目的,从而覆盖了该collectionViewContentSize方法.

尽管此方法CGSize在调用时返回有效值,但在实例化集合视图时,它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];
}
Run Code Online (Sandbox Code Playgroud)

另外,当我为UIcollectionView它明确定义静态帧时,它是按预期创建的,所以我知道我唯一的问题是使用该collectionViewContentSize方法.

所以我的问题是,我怎样才能动态设置我的高度UICollectionView

Cal*_*leb 8

集合视图滚动视图,因此您的-collectionViewContentSize方法是确定内容的大小,而不是整体视图的大小.您需要设置集合视图boundsframe属性以设置集合视图本身的大小.

您可能还想将它的scrollEnabled属性设置为NO在您使用它时.