UICollectionReusableView height based on UILabel text

I have a UICollectionReusableView that I would like to show in the header of my CollectionView.

I created an XIB file for the header and dragged a UICollectionReusableView and laid out the elements inside using auto-layout. The 2 labels inside the reusable presentation have dynamic content coming from the server, and therefore their height changes.

I would like to calculate the dynamic height at runtime and return it from:

collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize

I noticed that the height of the header view is always equal to the height specified in the XIB file.

enter image description here

+4
source share
1 answer

  CGRect requiredHeight;//

labelToUseInHeader = [self createLblWithfontStyle:@"thin" fontSize:16 frameDimen:CGRectMake(0, 0,collectionView.frame.size.width-16, 40) andTextColor:UIColorFromRGB(0x000000)];

CGSize constrainedSize = CGSizeMake(labelToUseInHeader.frame.size.width,9999);

NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:                                       [UIFont fontWithName:@"HelveticaNeue-Thin" size:16.0], NSFontAttributeName,nil];

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:"stringToProcessFromServer" attributes:attributesDictionary];

requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
requiredHeight = CGRectMake(0,0,labelToUseInHeader.frame.size.width, requiredHeight.size.height);

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {

        reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];

        if (reusableview==nil)
        {
            reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, collectionView.frame.size.width,200)];
        }

        labelToUseInHeader=[self createLblWithfontStyle:@"thin" fontSize:16 frameDimen:CGRectMake(8,0, collectionView.frame.size.width-16, 40) andTextColor:UIColorFromRGB(0x000000)];
        labelToUseInHeader.numberOfLines=0;
        labelToUseInHeader.userInteractionEnabled=NO;
        labelToUseInHeader.text="string from server";
        [labelToUseInHeader sizeToFit];

        [reusableview addSubview:labelToUseInHeader];
    }
    return nil;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{ 
return CGSizeMake(collectionView.frame.size.width,requiredHeight.size.height+10);//+10 for padding
 }
0

All Articles