4

我有一個UICollectionReusableView,我想在我的collectionView的標題中顯示。基於UILabel文字的UICollectionReusableView高度

我爲這個頭文件創建了一個XIB文件,並且拖拽了一個UICollectionReusableView,並在其中使用自動佈局來佈局這些元素。可重複使用視圖中的2個標籤具有來自服務器的動態內容,因此它們的高度各不相同。

我想在運行時計算動態高度和返回它:

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

我已經注意到的是,頭視線的高度總是等於在廈門國際銀行設定的高度文件。

enter image description here

+0

你有沒有解決這個問題? – 2017-02-24 18:47:03

回答

0

客觀c和編程 內景確實出現 的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 
}