22

I have the following code:

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

How do I get the height of label in points?

cdub
  • 24,555
  • 57
  • 174
  • 303

10 Answers10

60

The easiest way to get the height is sizeThatFits. Use it like this:

Objective-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))

The height your label needs is neededSize.height.
Note that im using CGFLOAT_MAX for the size height, to make sure the label has enough place to fit in the CGSize.

The height of your label also depends on your width of the label, thats why I added maxLabelWidth, it makes a difference if the label can be 100pt wide or 200pt.

Hope this helps!

Edit: Make sure you set label.numberOfLines = 0; otherwise neededSize returns the size where the text is in a single line.

Edit: Added Swift version, although the naming is a bit weird, greatestFiniteMagnitude seems to be the correct equivalent for CGFLOAT_MAX.

Fabio Berger
  • 1,921
  • 2
  • 24
  • 29
57

Use following method to calculate dynamic UILabel height:

- (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;
}
Philippe
  • 1,567
  • 16
  • 18
Salman Zaidi
  • 9,342
  • 12
  • 44
  • 61
7

Just use [label sizeThatFits:label.frame.size]; and it will return the size of label which will fit for given text. Or you can also follow the question

Community
  • 1
  • 1
iHulk
  • 4,869
  • 2
  • 30
  • 39
  • For Swift4 I user this: label.sizeThatFits(label.frame.size).height and it works perfectly, numberOfLines are 0 – clopex Nov 21 '19 at 09:42
6

For those who want to estimate the size a label takes in a method which estimates header / cell height in UICollectionView or UITableView, follow this:

  1. Set maxWidth that your label will take
  2. Create a new UILabel and set numberOfLines to 0
  3. Add Font attributes like custom font name and font size if using custom fonts
  4. Set text for this label and get estimated height using sizeThatFits. Label height is neededHeight.height

Swift Version

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

Thanks to @FabioBerger

kishorer747
  • 810
  • 1
  • 10
  • 24
2

I edited Salman Zaidi's answer a little to make it work better for myself. It works well if you don't have direct access to a label, like when you are trying to get label height in 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;
}
Shayno
  • 788
  • 9
  • 26
2

You can Create Label dynamically :

-(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;
}
sohil
  • 818
  • 2
  • 15
  • 38
1

I'm adjust height, with 2 lines in my label

lblUserQuestion.preferredMaxLayoutWidth = 100.0f;

100.0f, it's a size i wanted, and another line,

[lblUserQuestion sizeToFit];

My method complete is,

UILabel *lblUserQuestion = [[UILabel alloc] initWithFrame:CGRectMake(61, 25, self.frame.size.width-61-20, 37.0f)];
    lblUserQuestion.numberOfLines= 0;
    lblUserQuestion.font =[UIFont fontWithName:@"HelveticaNeue-Thin" size:14.];
lblUserQuestion.adjustsFontSizeToFitWidth = YES;
    lblUserQuestion.minimumScaleFactor = 0.5;
    lblUserQuestion.preferredMaxLayoutWidth= 100.0f;
    lblUserQuestion.text = _photoToVote.label; 
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;
}
Sargis
  • 1,196
  • 1
  • 18
  • 31
-2
 - (CGFloat)getLabelsize:(UILabel *)label
{
    CGSize maxSize = CGSizeMake(label.frame.size.width, 9999);
    CGSize requiredSize = [label sizeThatFits:maxSize];

    return requiredSize.height;
}
Ashokios
  • 27
  • 5
-2

Use this function

+ (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;
}
Sandeep Singh
  • 268
  • 1
  • 9