简体   繁体   中英

How to programmatically increase collection view cell height when label text increases?

How can I increase the height of the UICollectionViewCell? I have implemented 2 functionalities in my project:

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

And For image I used

- (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);

}

And for string I used

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

And in collection view layout

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

And I calculated the label function in

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)];

But the cell is not resizing if the label has lengthy name. Can you please help me?

Try this out or go through the link which I have put on comment.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM