本文介绍了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:
我非常希望计算单元的高度执行以下操作:
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动力高度与自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!