I am creating a UI based on horizontally scrolling cards. All set and one but, some cards are now bigger (more content) than the others. In this case, I guess my solution won't work because I calculate the flow layout size like this:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake((collectionView.frame.size.width-30)/2,(collectionView.frame.size.height);
}
This restricts cell's height. Is it even possible to have a dynamic height of UICollectionViewCells for horizontal layout? No clues found on the web. Please help !!
- (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;
}
You have to calculate the height of each texts inside collection view cell dynamically.
See below code and update according to your requirements.
- (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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.