4

我有一个 UICollectionReusableView,我想在我的 collectionView 的标题中显示它。

我为标题创建了一个 XIB 文件并拖动了一个 UICollectionReusableView 并使用自动布局在其中布置了元素。可重用视图中的 2 个标签具有来自服务器的动态内容,因此它们的高度会有所不同。

我想在运行时计算动态高度并从以下位置返回:

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

我注意到的是标题视图的高度总是等于在 XIB 文件中设置的高度。

在此处输入图像描述

4

1 回答 1

0

对于objective c和programmatically inside view确实出现了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
 }
于 2015-02-24T07:06:25.203 回答