1

我有一个UICollectionView2UILabelUIImage一个类似的布局:

 --------------------
 |                   |
 |    LABEL1         |
 |    IMAGE          |
 |    LABEL2         |
 |    ......         |
 |    ......         |
 --------------------

Label2 具有可变数量的行,在单元格之间有所不同,我希望能够根据 自动调整大小UICollectionView heightlabel2 height让它“自动填充”单元格。在iOS中可以做到吗?

4

1 回答 1

0

您可以重写以下方法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;
}
于 2013-01-10T11:10:30.833 回答