带有自动布局的 UICollectionViewCell 动态高度 [英] UICollectionViewCell dynamic height with autolayout
本文介绍了带有自动布局的 UICollectionViewCell 动态高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 UICollectionViewCell 的自动布局.所以这个想法是允许 CollectionViewCell 根据布局确定它的大小.所有约束都设置正确,但问题是我无法计算数据源方法的大小
I am using auto layout with UICollectionViewCell. So the idea is to allow CollectionViewCell to determine it's size based on layouts. All the constraints are set properly but the problem is that I can not calculate it's size for data source method
collectionView:layout:sizeForItemAtIndexPath:
理想情况下,我想通过以下方式计算 Cell 的高度:
Ideally I would like to calculate Cell's height doing the following:
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;
但它不会强制更新约束,因此单元格的框架为零.你能告诉我如何根据它的约束来计算单元格的大小吗?
but it doesn't force constraints to update, so the cell's frame is zero. Can you advice me how can I calculate cell's size based on it's constraints?
谢谢
推荐答案
这里是解决方案
- (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;
}
这篇关于带有自动布局的 UICollectionViewCell 动态高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文