【问题标题】:Calculate dynamic cell height for a horizontal UICollectionView in iOS计算 iOS 中水平 UICollectionView 的动态单元格高度
【发布时间】:2017-09-07 06:06:54
【问题描述】:

我正在创建一个基于水平滚动卡片的 UI。全部设置,但是,现在有些卡比其他卡更大(更多内容)。在这种情况下,我想我的解决方案不会起作用,因为我这样计算流布局大小:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((collectionView.frame.size.width-30)/2,(collectionView.frame.size.height);
} 

这限制了单元格的高度。甚至可以为水平布局设置 UICollectionViewCells 的动态高度吗?网上没有找到任何线索。请帮忙!!

【问题讨论】:

    标签: ios objective-c uicollectionview uicollectionviewlayout


    【解决方案1】:
     - (CGSize)calculateSizeForSizingCell:(UICollectionViewCell *)sizingCell width:(CGFloat)width {
    CGRect frame = sizingCell.frame;
    frame.size.width = width;
    sizingCell.frame = frame;
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];
    
    CGSize size = [sizingCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize
                        withHorizontalFittingPriority:UILayoutPriorityRequired
                              verticalFittingPriority:UILayoutPriorityFittingSizeLevel];
    return size;
     }
    

    【讨论】:

      【解决方案2】:

      您必须动态计算集合视图单元格内每个文本的高度。

      查看以下代码并根据您的要求进行更新。

      - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
      
          NSMutableDictionary *currentObject = [yourMutableArray objectAtIndex:indexPath.row];
          CGFloat cvWidth = (collectionView.frame.size.width-30)/2;
          CGSize rect;
      
          CGFloat heightOfText = [self getTextHeightFromString:[currentObject valueForKey:@"yourKeyName"] ViewWidth:cvWidth WithPading:10];
      
          CGFloat heightOfSecondText = [self getTextHeightFromString:[currentObject valueForKey:@"yourSecondKeyName"] ViewWidth:cvWidth WithPading:10];
      
          //get height of each and every text and calculate total height
      
          rect.width = cvWidth;
          rect.height = heightOfText + heightOfSecondText;
      
          return rect;
      
      }
      
      - (CGFloat)getTextHeightFromString:(NSString *)text ViewWidth:(CGFloat)width WithPading:(CGFloat)padding
      {
          CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:@{NSFontAttributeName: [UIFont fontWithName:@"yourFontName" size:16]} // change font size accordingly
                                           context:nil];
      
          return rect.size.height + padding;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-27
        • 2015-03-25
        • 2018-11-09
        相关资源
        最近更新 更多