UILabel 根据长度自动高度 ios

UILabel automatic height as per the length ios

我有一个 UICollectionView,如图所示 below.The titleLabel 如您所见,它的高度应该根据 content.the 背景视图 labelView 也应该更改它的 height.How 我可以这样做吗?

我用过...

-(CGFloat) heightForText:(NSString *)text withWidth:(CGFloat) textWidth{

    CGSize constraint = CGSizeMake(textWidth, 20000.0f);
    CGRect rect = [text boundingRectWithSize:constraint
                       options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                    attributes:@{NSFontAttributeName:cell.titleLabel.font}
                       context:nil];
    CGFloat height = rect.size.height;

    height = ceilf(height);
//    NSLog(@"height %f", height);
    return height;
}

我用这个就像...

CGRect newFrame = cell.titleLabel.frame;
      newFrame.size.height = height;
       cell.titleLabel.frame = newFrame;

我正在将新框架添加到 label.but 高度从固定的 y 增加到 down.Here 现在我必须根据 height.Is 以任何其他方式提升 y ?

方法来了

-(CGFloat) heightForText:(NSString *)text withWidth:(CGFloat) textWidth{

    CGSize constraint = CGSizeMake(textWidth, 20000.0f);
    CGRect rect = [text boundingRectWithSize:constraint
                       options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                    attributes:@{NSFontAttributeName:cell.titleLabel.font}
                       context:nil];
    CGFloat height = rect.size.height;

    height = ceilf(height);
//    NSLog(@"height %f", height);
    return height;
}

使用ankit的代码获取label需要的Height,使用autoLayout如下图

添加一个 视图 ---> 设置前导、尾随和底部约束 相对于单元格超级视图。

然后将标签作为子视图添加到此view.ADD所有四个constraints.ie,设置前导、尾随、顶部和底部约束

现在,使用上面Ankit的代码(我已经粘贴在下面)获取标签的高度并将其设置为标签框架。

-(CGFloat) heightForText:(NSString *)text withWidth:(CGFloat) textWidth{

    CGSize constraint = CGSizeMake(textWidth, 20000.0f);
    CGRect rect = [text boundingRectWithSize:constraint
                       options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                    attributes:@{NSFontAttributeName:cell.titleLabel.font}
                       context:nil];
    CGFloat height = rect.size.height;

    height = ceilf(height);
//    NSLog(@"height %f", height);
    return height;
}

现在将新框架设置为标签。

CGRect newFrame = cell.titleLabel.frame;
      newFrame.size.height = height;
       cell.titleLabel.frame = newFrame;

希望它有用。这一切都是关于正确设置自动布局。试试看,让我知道。