如何动态计算UILabel高度

时间:2014-12-09 08:44:31

标签: ios objective-c iphone ios8 uilabel

我有以下代码:

label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = @"some long text";
[label sizeToFit];

如何获得分数的标签高度?

10 个答案:

答案 0 :(得分:51)

使用以下方法计算动态UILabel高度:

- (CGFloat)getLabelHeight:(UILabel*)label
{
    CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
    CGSize size;

    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:label.font}
                                                  context:context].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}

答案 1 :(得分:51)

获得身高的最简单方法是sizeThatFits。像这样使用它:

目标-C

CGFloat maxLabelWidth = 100;
CGSize neededSize = [label sizeThatFits:CGSizeMake(maxLabelWidth, CGFLOAT_MAX)];

Swift 3.0

let maxLabelWidth: CGFloat = 100
let neededSize = label.sizeThatFits(CGSize(width: maxLabelWidth, height: CGFloat.greatestFiniteMagnitude))

标签所需的高度为neededSize.height 请注意,我使用CGFLOAT_MAX作为尺寸高度,以确保标签有足够的位置适合CGSize

标签的高度还取决于标签的宽度,这就是我添加maxLabelWidth的原因,如果标签宽度为100pt或200pt,则会有所不同。

希望这有帮助!

修改 请确保设置label.numberOfLines = 0;,否则neededSize会返回文本在一行中的大小。

修改 添加了Swift版本,虽然命名有点奇怪,但是greatFiniteMagnitude似乎是CGFLOAT_MAX的正确等价物。

答案 2 :(得分:6)

只需使用[label sizeThatFits:label.frame.size];,它将返回适合给定文字的标签大小。或者您也可以关注question

答案 3 :(得分:5)

对于那些想要估算标签大小的人来说,在UICollectionView或UITableView中估算标题/单元格高度的方法,请按照:

  1. 设置标签将采用的maxWidth
  2. 创建一个新的UILabel并将numberOfLines设置为0
  3. 如果使用自定义字体
  4. ,请添加自定义字体名称和字体大小等字体属性
  5. 设置此标签的文字,并使用sizeThatFits获取估计的高度。标签高度为neededHeight.height
  6. Swift 版本

    let maxLabelWidth:CGFloat = collectionView.frame.width - 20
    let label = UILabel()
    label.numberOfLines = 0
    let addressFont = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 12.0)! ]
    let addr = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    label.attributedText = NSMutableAttributedString(string: addr , attributes: addressFont )
    let neededSize:CGSize = label.sizeThatFits(CGSizeMake(maxLabelWidth, CGFloat.max))
    let labelHeight = neededSize.height
    

    感谢@FabioBerger

答案 4 :(得分:2)

我编辑了Salman Zaidi的答案,以使其更适合我自己。如果您无法直接访问标签,例如在heightForRowAtIndexPath:

中尝试获取标签高度时,它就会很有效
-(CGFloat)getLabelHeight:(CGSize)labelSize string: (NSString *)string font: (UIFont *)font{

    CGSize size;

    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [string boundingRectWithSize:labelSize
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:font}
                                                  context:context].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}

答案 5 :(得分:2)

您可以动态创建标签:

-(CGRect)newLableSize:(NSString *)lableString
{
     NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
     [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];

        CGFloat tempwidth = YourStaticLabelWidth * ScreenWidth / 320;
        NSMutableArray *array=[[NSMutableArray alloc]initWithObjects: lableString,nil];
       CGRect newLabelsize = [[array objectAtIndex:0] boundingRectWithSize:CGSizeMake(tempwidth, MAXFLOAT)  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:selectFont,NSParagraphStyleAttributeName:paragraphStyle} context:nil];   

        NSLog(@"New Label Size Width  : %f",newLabelsize.size.width);
        NSLog(@"New Label Size Height : %f",newLabelsize.size.height);

        return newLabelsize;
}

答案 6 :(得分:1)

我调整了身高,我的$ sudo port -f uninstall python $ sudo port install python +universal $ sudo port install boost +universal

中有2行

label

100.0f,这是我想要的尺寸,另一条线,

lblUserQuestion.preferredMaxLayoutWidth = 100.0f;

我的方法完成了,

[lblUserQuestion sizeToFit];

答案 7 :(得分:1)

- (CGFloat)getTextHeightByWidth:(NSString*)text textFont:(UIFont*)textFont textWidth:(float)textWidth {

    if (!text) {
        return 0;
    }
    CGSize boundingSize = CGSizeMake(textWidth, CGFLOAT_MAX);
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{ NSFontAttributeName: textFont }];

    CGRect rect = [attributedText boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    CGSize requiredSize = rect.size;
    return requiredSize.height;
}

- (CGFloat)getTextWidthByHeight:(NSString*)text textFont:(UIFont*)textFont textHeight:(float)textHeight {

    if (!text) {
        return 0.0f;
    }
    CGSize boundingSize = CGSizeMake(CGFLOAT_MAX, textHeight);

    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text
                                                                         attributes:@{ NSFontAttributeName: textFont }];

    CGRect rect = [attributedText boundingRectWithSize:boundingSize
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize requiredSize = rect.size;
    return requiredSize.width;
}

答案 8 :(得分:-2)

 - (CGFloat)getLabelsize:(UILabel *)label
{
    CGSize maxSize = CGSizeMake(label.frame.size.width, 9999);
    CGSize requiredSize = [label sizeThatFits:maxSize];

    return requiredSize.height;
}

答案 9 :(得分:-2)

使用此功能

+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {

    CGSize constraint = CGSizeMake(width, 20000.0f);
    CGSize size;

    CGSize boundingBox = [text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:font}
                                                  context:nil].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}