以编程方式在UICollectionViewController的单元格内设置UIView子视图的高度?

Zac*_*urt 5 subview uiview ios uicollectionviewcell

在我的单元格的可重用视图内,我有一个UIView.

然后,我在控制器中有这个方法

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    // .. set value for CGFloat backgroundHeight

    [cell addSubview:cell.backgroundView];

    CGRect f = cell.backgroundView.frame;
    f.size.height = backgroundHeight;
    cell.backgroundView.frame = f;

}
Run Code Online (Sandbox Code Playgroud)

但是UIView的高度保持与Layout Rectangle中指定的相同.

我接下来应该尝试什么?

Sun*_*hah 1

您可以使用 sizeForItemAtIndexPath 管理布局高度

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    return CGSizeMake(view.frame.size.width, view.frame.size.height);
}
Run Code Online (Sandbox Code Playgroud)
here  you can manage spacing
Run Code Online (Sandbox Code Playgroud)
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5,5,0,5);
}
Run Code Online (Sandbox Code Playgroud)