36

I'm getting the width of a UILabel [after the text has been set] with:

myUILabel.frame.width

but its always the same width, no matter if it holds the String: "Hello." or the String: "Hello everyone on this planet.". But the UILabel needs to have a bigger width with the second String.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
Megaetron
  • 1,154
  • 2
  • 15
  • 29
  • use [myUILabel sizeToFit]; also we can calculate width using like http://stackoverflow.com/questions/1340667/pixel-width-of-the-text-in-a-uilabel – Venk May 27 '15 at 12:07
  • For what do you need width? And are you using auto layout ? If you are using auto layout you can get rid of it by playing with content hugging priority so frame.width will return correct value – Zell B. May 27 '15 at 12:16
  • 1
    You could look at the intrinsic content size of a label which has to do with auto layout and layout constraints. Just google it, maybe you even actually want to use auto layout when you want to know the label's width. – borchero May 27 '15 at 15:24

3 Answers3

71

Try myUILabel.intrinsicContentSize(). Make sure you set your font first, of course.

Jolly Roger
  • 3,913
  • 4
  • 24
  • 23
3

You should use [label sizeToFit]

sizeToFit on label will stretch the label to accommodate the text.

The other solution is to calculate the width of the string and reframe the label based on the strings width.

For the second solution you can calculate the size of string as

CGSize strSize = CGSizeZero;

CGSize minSize = CGSizeZero;

if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
    NSAttributedString *attributedText = [[[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: label.font}] autorelease];
    CGRect rect = [attributedText boundingRectWithSize:constraintSize
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    strSize = rect.size;
}
else
{
    strSize = [text sizeWithFont:label.font constrainedToSize:constraintSize];
}
Sanjay Mohnani
  • 5,947
  • 30
  • 46
3

Try

     myUILabel.intrinsicContentSize.width

Or

     myUILabel.intrinsicContentSize().width
Grenoblois
  • 503
  • 1
  • 5
  • 19