繁体   English   中英

计算iOS中水平UICollectionView的动态单元格高度

[英]Calculate dynamic cell height for a horizontal UICollectionView in iOS

我正在创建基于水平滚动卡的UI。 全部设置了一张,但是,有些卡现在比其他卡更大(内容更多)。 在这种情况下,我想我的解决方案将无法正常工作,因为我按如下方式计算流程布局大小:

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

这限制了单元格的高度。 甚至有可能具有用于水平布局的UICollectionViewCells动态高度? 在网络上找不到任何线索。 请帮忙 !!

 - (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;
 }

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

请参阅以下代码,并根据您的要求进行更新。

- (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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM