具有自动布局的UICollectionViewCell动态高度

Leo*_*nid 10 autolayout uicollectionview nslayoutconstraint uicollectionviewcell

我正在使用UICollectionViewCell的自动布局.因此,我们的想法是允许CollectionViewCell根据布局确定它的大小.所有约束都设置正确,但问题是我无法计算数据源方法的大小

collectionView:layout:sizeForItemAtIndexPath:
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想计算Cell的高度,执行以下操作:

static MyCell *myCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    myCell = [[MyCell alloc] initWithFrame:CGRectZero];
});
cell.model = model;
[cell updateConstraints];
[cell layoutSubviews];
return cell.frame.size;
Run Code Online (Sandbox Code Playgroud)

但它不会强制更新约束,因此单元格的框架为零.你能建议我如何根据它的约束来计算细胞的大小?

谢谢

Mih*_*awk 8

这是解决方案

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YourCollectionCell * cell = (YourCollectionCell *) [YourCollectionViewObj cellForItemAtIndexPath:indexPath];

            if (cell == nil) {

                NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"YourCollectionCell" owner:self options:nil];
                cell = [topLevelObjects objectAtIndex:0];
                cell.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 20);
                // SET YOUR CONTENT
                [cell layoutIfNeeded];

            }

            CGSize CellSize = [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize withHorizontalFittingPriority:UILayoutPriorityDefaultHigh verticalFittingPriority:UILayoutPriorityDefaultLow];


            return CellSize;
 }
Run Code Online (Sandbox Code Playgroud)


小智 0

我认为你应该返回这个尺寸:

return [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

19307 次

最近记录:

9 年,5 月 前