动态调整 UICollectionViewCell 的大小 [英] Dynamically resizing a UICollectionViewCell
问题描述
我有一个带有 2 个 UILabel
的 UICollectionView
和一个具有类似布局的 UIImage
:
I have a UICollectionView
with 2 UILabel
and a UIImage
with a similar layout:
--------------------
| |
| LABEL1 |
| IMAGE |
| LABEL2 |
| ...... |
| ...... |
--------------------
Label2 的行数可变,单元格之间不同,我希望能够根据 label2 height
自动调整 UICollectionView 高度
,让它自动填充"单元格.在 iOS 中可以做到吗?
Label2 has a variable number of lines, different between cells, and I would like to be able to autosize the UICollectionView height
according to label2 height
, to let it "autofill" the cell.
Is it possible to do it in iOS?
推荐答案
您可以重写UICollectionViewDelegateFlowLayout
的以下方法来动态计算 UICollectionViewCell 的高度,根据需要设置常量值.
You can override following method of UICollectionViewDelegateFlowLayout
to dynamically calculate height of UICollectionViewCell, set the constant values according to your requirements.
-(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;
}
这篇关于动态调整 UICollectionViewCell 的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!