I have one Image and one Label. Image is fix but the label is variable. So, the size of the label may vary. So, i want to change the height of the cell.
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return questions.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
SymbolCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
Question *q = [questions objectAtIndex:indexPath.row];
NSString *image = q.ImageName;
cell.imgSymbol.image = [UIImage imageNamed:image];
cell.lblName.text = q.Answer;
return cell;
}
Use this method to return cell width and height.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
SymbolCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
Question *q = [questions objectAtIndex:indexPath.row];
NSString *image = q.ImageName;
cell.imgSymbol.image = [UIImage imageNamed:image];
cell.lblName.frame = CGRectMake(cell.lblName.frame.origin.x , cell.imgSymbol.frame.origin.y+8, cell.lblName.frame.size.width, 21);
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:q.Answer];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, str.length)];
cell.lblName.attributedText = str;
[cell.lblName setNumberOfLines:0];
[cell.lblName sizeToFit];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
// calculate label height here
Question *q = [questions objectAtIndex:indexPath.row];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:q.Answer];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, str.length)];
CGSize sizeName = CGRectIntegral([str boundingRectWithSize:CGSizeMake("YorLabel Width", MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil]).size;
// give here cell width and height
return CGSizeMake((collectionView.frame.size.width-20)/3, sizeName.height+YourImage height + spec); // here return your cell height
}
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.