ios - UICollectionViewCell 高度基于标签大小

标签 ios objective-c uicollectionviewcell uicollectionviewlayout custom-cell

我有一个包含 UICollectionView 的 View ,它加载 UICollectionViewCell 的外部 cellnib 文件。我的数据按照我想要的方式正确显示。我想根据其中的文本标签保留单元格高度,但我不确定下面的代码中缺少什么。我尝试过查看答案,但对于如何解决它没有多大意义。请帮忙。提前致谢。

  - (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell =  (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@" mycell" forIndexPath:indexPath];

    NSString *string = cell.lblContact.text;
    CGSize size = [self getLabelSize:string];
    NSLog(@"%f and %f",size.width ,size.height);

   return cell;
}

- (CGSize)getLabelSize:(NSString *)string {

    UIFont *updatedFont = [UIFont fontWithName:@"myFont" size:18.0];
    CGRect rect = [string boundingRectWithSize:(CGSize){maxWidth, CGFLOAT_MAX} options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName: updatedFont } context:nil];
    return rect.size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize retval = CGSizeMake(collectionView.frame.size.width, 75);
    return retval;
}

- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section 
{
     return UIEdgeInsetsMake(0, 0, 0, 0);
}

最佳答案

我找到了解决方案。我在 sizeForItemAtIndexPath 中创建了一个字符串,它从与 cell.lblContact.text 相同的位置获取值。

MyObject *mc = (MyObject *) [contactArray objectAtIndex:indexPath.row];
NSString *myString = mc.contactName;
CGSize size = [self getLabelSize:myString];
NSLog(@"%@", myString);
NSLog(@"%f", size.height);

if (myString.length > 25) {
    CGSize retval = CGSizeMake(collectionView.frame.size.width, size.height);
    [collectionView layoutIfNeeded];
    return retval;
} else {
    CGSize retval = CGSizeMake(collectionView.frame.size.width, 75);
    return retval;
}

关于ios - UICollectionViewCell 高度基于标签大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31027630/

相关文章:

ios - 自定义CollectionViewCell

ios - Result.Framework 未在 TrueTime 中找到?

ios - 在 Storyboard (iOS) 中添加/删除特定大小类的约束

objective-c - MFMailComposeViewController 中的 iOs 自定义方案

ios - 即使没有编写警报代码,在前台推送通知时也会在 iOS 10 中发出警报

ios - 如何使用新 API willAnimateRotationToInterfaceOrientation 修复 iOS 方向

ios - 如何使自定义 collectionview 单元格可见?

ios - 调整 UICollectionViewCell 的大小

ios - 尝试将数据存储在类中,更改 View Controller 时返回 nil

ios - 将 TextField 输入限制为大写字母、数字和 6 个字符限制?