我正在创建一个基于水平滚动卡片的UI。所有设置和一个,但有些卡现在比其他卡更大(更多的内容)。在这种情况下,我想我的解决方案不会起作用,因为我计算了这样的流程布局大小:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake((collectionView.frame.size.width-30)/2,(collectionView.frame.size.height);
}
这限制了细胞的高度。甚至可以为水平布局设置动态高度的UICollectionViewCells吗?在网上找不到任何线索。请帮忙!!
答案 0 :(得分:0)
- (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;
}
答案 1 :(得分:0)
您必须动态计算集合视图单元格内每个文本的高度。
请参阅以下代码并根据您的要求进行更新。
- (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;
}