基于UILabel的UICollectionViewCell AutoLayout动态高度

Posted

技术标签:

【中文标题】基于UILabel的UICollectionViewCell AutoLayout动态高度【英文标题】:UICollectionViewCell AutoLayout dynamic height based on UILabel 【发布时间】:2015-04-29 02:38:05 【问题描述】:

我正在使用 UICollectionViewCell 的自动布局和大小类。所以我们的想法是制作一个与 Instagram 相似的 UI。

问题是我无法完全理解如何添加正确的自动布局,因为似乎添加缺少的约束并没有神奇地做到这一点。

当我添加约束时,即使没有警告,它总是在目标输出上显示“将尝试通过打破约束来恢复”。目标是根据 iphone 类型使配置文件单元格动态化,并根据 bioLabel 动态化高度。现在我把它设为静态,这是非常错误的,因为当我使用这种方法时

systemLayoutSizeFittingSize:UILayoutFittingCompressedSize

它总是返回零,我猜是因为自动布局约束放错了位置。你能告诉我如何根据它的约束计算单元格的大小吗?我已经在 github 上创建了这个项目,任何帮助将不胜感激!

CollectionViewAutoLayout

【问题讨论】:

【参考方案1】:

我下载了您的代码并发现了问题。看,你可以通过在你的 collectionView:layout:sizeForItemAtIndexPath 方法中替换这行代码来解决你的问题。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
    if (indexPath.section == 0) 
        CGFloat height = [self findHeightForText:@"Description about yourself, who you are and what impact did you do to the environment. did you do to the environment. Description about yourself, who you are and what impact did you do to the environment. did you do to the environment. who you are and what impact did you do to the environment. did you do to the environment. who you are and what impact did you do to the environment. did you do to the environment." havingMaximumWidth:[UIScreen mainScreen].bounds.size.width andFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]];
        return CGSizeMake([UIScreen mainScreen].bounds.size.width, 150 + height);
    
    else 
        return CGSizeMake((([UIScreen mainScreen].bounds.size.width - 2.0) / 3.0), (([UIScreen mainScreen].bounds.size.width - 4.0) / 3.0));
    

添加此方法动态计算高度。

 #pragma mark - Height Calculation Method
- (CGFloat)findHeightForText:(NSString *)text havingMaximumWidth:(CGFloat)widthValue andFont:(UIFont *)font 
    CGSize size = CGSizeZero;
    if (text) 
        //ios 7
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@ NSFontAttributeName:font  context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height + 1);
    
    return size.height;

更换一次并在所有设备上进行测试,然后告诉我...希望对您有所帮助:)

【讨论】:

谢谢你!它解决了这个问题,但是自动布局呢?你能给出建议如何使它正确吗?所以我可以理解自动布局是如何工作的。但我现在会接受你的回答。

以上是关于基于UILabel的UICollectionViewCell AutoLayout动态高度的主要内容,如果未能解决你的问题,请参考以下文章

基于UILabel的UICollectionViewCell AutoLayout动态高度

基于标签的多功能UIButton更改UILabel的线程中断

在 uiTableViewCell 中更改 UILabel 的属性

UILabel 不会在 TableViewCell 中的初始加载时换行

具有动态 UILabel 和内容压缩/阻力的 UITableViewCell 高度不正确

将 UILabel 添加到子视图后如何重写它?