您可以重写以下方法UICollectionViewDelegateFlowLayout
来动态计算 UICollectionViewCell 的高度,根据您的要求设置常量值。
-(CGSize) collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
UIFont *fontLabel1 = [UIFont systemFontOfSize:17];
UIFont *fontLabel2 = [UIFont systemFontOfSize:14];
int padding = 5;
int maxWidthOfLabel = 300;
CGSize maximumLabelSize = CGSizeMake(maxWidthOfLabel, CGFLOAT_MAX);
NSString *strLabel1 = @"Label one text";// Get text for label 1 at indexPath
NSString *strLabel2 = @"Label two text";// Get text for label 2 at indexPath
NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;
NSDictionary *attr1 = @{NSFontAttributeName: fontLabel1};
NSDictionary *attr2 = @{NSFontAttributeName: fontLabel2};
// Calculate individual label heights
CGFloat heightLabel1 = [strLabel1 boundingRectWithSize:maximumLabelSize
options:options
attributes:attr1
context:nil].size.height;
CGFloat heightLabel2 = [strLabel2 boundingRectWithSize:maximumLabelSize
options:options
attributes:attr2
context:nil].size.height;
CGSize sizeOfImage = CGSizeMake(50, 50);
// Calculate height based on all Views (2 Labels + 1 ImageView)
CGFloat height = heightLabel1+heightLabel2+sizeOfImage.height+2*padding;
CGFloat width = collectionView.frame.size.width;// Set width
CGSize size = CGSizeMake(width, height);
return size;
}