标签文本增加时如何以编程方式增加集合视图单元格高度?

Posted

技术标签:

【中文标题】标签文本增加时如何以编程方式增加集合视图单元格高度?【英文标题】:How to programmatically increase collection view cell height when label text increases? 【发布时间】:2018-08-13 10:14:41 【问题描述】:

如何增加 UICollectionViewCell 的高度?我在我的项目中实现了 2 个功能:

- (NSArray *)cellSizes 

/** Here we mentioned the code for size of collection view cells  **/
_cellSizes = [NSMutableArray array];

if ([homePageArray count] != 0 )

    _cellSizes = [NSMutableArray array];
    [_cellSizes removeAllObjects];

    for (NSInteger i = 0; i < [homePageArray count]; i++)
    
        CGSize size;
        UIImageView *sampleImage = [[[UIImageView alloc]init]autorelease];
        [sampleImage setFrame:CGRectMake(0,0,(delegate.windowWidth-30),150)];
        CGSize size1 = [self aspectScaledImageSizeForImageView:sampleImage width:150 height:150];
        //        [productTitleLbl setFont:[UIFont fontWithName:appFontRegular size:14]]; //78 //60
        CGFloat heightOfStr = [self heightForString:[[homePageArray objectAtIndex:i]objectForKey:@"item_title"] font:[UIFont fontWithName:appFontRegular size:14] maxWidth:(delegate.windowWidth-35)];

        size=CGSizeMake(size1.width, size1.height+((heightOfStr>30)?heightOfStr+55:85));
        _cellSizes[i] =[NSValue valueWithCGSize:size];
    

return _cellSizes;

对于我使用的图像

- (CGSize) aspectScaledImageSizeForImageView:(UIImageView *)iv width:(float)wid height:(float)hgth


float x,y;
float a,b;
x = iv.frame.size.width;
y = iv.frame.size.height;
a = wid;
b = hgth;

if ( x == a && y == b )            // image fits exactly, no scaling required
    // return iv.frame.size;

else if ( x > a && y > b )          // image fits completely within the imageview frame
    if ( x-a > y-b )               // image height is limiting factor, scale by height
        a = y/b * a;
        b = y;
     else 
        b = x/a * b;                // image width is limiting factor, scale by width
        a = x;
    

else if ( x < a && y < b )         // image is wider and taller than image view
    if ( a - x > b - y )           // height is limiting factor, scale by height
        a = y/b * a;
        b = y;
     else                         // width is limiting factor, scale by width
        b = x/a * b;
        a = x;
    

else if ( x < a && y > b )         // image is wider than view, scale by width
    b = x/a * b;
    a = x;

else if ( x > a && y < b )         // image is taller than view, scale by height
    a = y/b * a;
    b = y;

else if ( x == a ) 
    a = y/b * a;
    b = y;
 else if ( y == b ) 
    b = x/a * b;
    a = x;



return CGSizeMake(a,b);


对于我使用的字符串

- (CGFloat)heightForString:(NSString *)text font:(UIFont *)font maxWidth:(CGFloat)maxWidth 
if (![text isKindOfClass:[NSString class]] || !text.length) 
    // no text means no height
    return 0;


NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
NSDictionary *attributes = @ NSFontAttributeName : font ;
CGSize size = [text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) options:options attributes:attributes context:nil].size;
CGFloat height = ceilf(size.height) + 1; // add 1 point as padding

return height;

在集合视图布局中

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath


if([homePageArray count]!=0)
    return [self.cellSizes[indexPath.item] CGSizeValue];
else
    return CGSizeMake(0, 0);

我在

中计算了标签函数
CGFloat HeightForString = [self heightForString:[[homePageArray objectAtIndex:indexPath.row]objectForKey:@"item_title"] font:[UIFont fontWithName:appFontRegular size:14] maxWidth:cell.frame.size.width];
        [cell.productTitleLbl setFrame:CGRectMake(10, cell.frame.size.height-60, cell.frame.size.width,(HeightForString>30)?HeightForString:30)];

但如果标签的名称很长,则单元格不会调整大小。你能帮帮我吗?

【问题讨论】:

告诉集合视图重新加载数据,以便再次调用sizeForItem ***.com/questions/18897896/… 【参考方案1】:

试试这个或浏览我发表评论的链接。

 itemTitleText =[[self.jsonData 
 objectAtIndex:indexPath.row]objectForKey:@"item_title"];


 NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[itemTitleText 
 dataUsingEncoding:NSUTF8StringEncoding] options:@NSDocumentTypeDocumentAttribute: 
 NShtmlTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber 
 numberWithInt:NSUTF8StringEncoding] documentAttributes:nil error:nil];


    CGRect labelRect = [itemTitleText
                        boundingRectWithSize:CGSizeMake(270, CGFLOAT_MAX)
                        options:NSStringDrawingUsesLineFragmentOrigin
                        attributes:@
                         NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue- 
   Medium" size:14.0]
                                     
                        context:nil];
    cell.itemTitleText.frame=CGRectMake(cell.itemTitleText.frame.origin.x, 
     cell.itemTitleText.frame.origin.y, cell.itemTitleText.frame.size.width, 
    labelRect.size.height);

【讨论】:

以上是关于标签文本增加时如何以编程方式增加集合视图单元格高度?的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式添加内容时如何增加表格单元格的高度?

如何根据标签文本快速更改表格视图单元格高度?

根据单元格OBjective-C中的标签文本(动态)增加单元格高度

如何使用故事板中定义的单元格计算集合视图单元格高度?

如何根据swift 3中的集合视图高度动态增加表格视图高度?

tableview不同的单元格在swift中有不同的高度