2014-10-11 85 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