2014-10-11 45 views
0

我想根據單元格內容(特別是UILabel)的大小更改UICollectionViewCell的高度。我設置的UILabel高度UICollectionViewCell的設置高度

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionViewcellForItemAtIndexPath:(NSIndexPath *)indexPath 

然後我設置UICollectionViewCell高度

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

它出現的第二個方法是在第一個調用之前,所以標籤的高度還沒有被計算。完整的代碼發現如下(警告:需要一個整潔!)。有任何想法嗎?

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
       cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *myCell = [collectionView 
            dequeueReusableCellWithReuseIdentifier:@"Cell" 
            forIndexPath:indexPath]; 


    label = [[UILabel alloc] initWithFrame:CGRectMake(80,10,width - 90,0)]; 
    label.text = @"Hellfoneofinerigoneriognwirotngwtngowirnthointgonowenfkqejb fgjkreb glknrlegkn ewlj qerlgjnweofjpeorihgpireghiperhgorgrngl;rtnh;ltm;l"; 
    label.lineBreakMode = NSLineBreakByWordWrapping; 
    label.numberOfLines = 0; 
    label.font = [UIFont fontWithName:@"HelveticaNeue-UltraLight" size:17]; 
    [label sizeToFit]; 

    [myCell.contentView addSubview:label]; 
    CGSize labelY = [label bounds].size; 
    i = labelY.height; 
    NSLog(@"Height: %d", i); 


     return myCell; 
} 

#pragma mark <UICollectionViewDelegate> 
- (CGSize)collectionView:(UICollectionView *)collectionView 
        layout:(UICollectionViewLayout *)collectionViewLayout 
    sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 

NSLog(@"Height: %d", i); 

    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) 
    { 
     CGSize result = [[UIScreen mainScreen] bounds].size; 
     if(result.height == 568) 
     { 
      return CGSizeMake(300.f, i); 

     } 
     if(result.height == 667) 
     { 
      return CGSizeMake(340.f, i); 

     } 
     if(result.height == 736) 
     { 
      return CGSizeMake(370.f, i); 


     } 
    } 
    return CGSizeMake(300.f, i); 

} 

編輯:沒有真正解釋錯誤。當調用-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath .時,i的高度等於零。

回答

0

通過在高度方法中創建一個標籤並確定高度來工作。

0

佈局委託方法- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
數據源方法-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath,以及所有的單元的sizeForItemAtIndexPath計算大小之前首先執行,然後開始建立它們。

所以,你應該只獲取由indexPath的內容,然後計算高度顯示,在cellForItemAtIndexPath

0

應用高度值你所試圖實現自上漿UICollectionViewCell秒。要實現,你需要:

  • 設置estimatedItemSize爲的FlowLayout
  • 針標籤的頂部,底部,領導和後緣
  • 確保Vertical Content Hugging Priority的最後一個標籤是250
  • 和實施preferredLayoutAttributesFitting在UICollectionViewCell

我寫了一個較長的博客帖子大約自上漿UICollectinViewCell這兒: http://parveenkaler.com/posts/self-sizing-uicollectionviewcell-swift