Dynamically resizing a UICollectionViewCell

北城余情 提交于 2019-12-12 10:16:21

问题


I have a UICollectionView with 2 UILabel and a UIImage with a similar layout:

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

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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/14255692/dynamically-resizing-a-uicollectionviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!