How to get the correct width of a UILabel after the text has been set?
Asked Answered
E

3

37

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.

Earleanearleen answered 27/5, 2015 at 12:6 Comment(3)
use [myUILabel sizeToFit]; also we can calculate width using like #1341167Ghana
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 valueBragg
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.Rocha
R
76

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

Reinhold answered 2/4, 2016 at 17:38 Comment(2)
To get the width use: myUILabel.intrinsicContentSize.widthCandlepower
thank you for the help. i was trang using constratings in storyboard.Crimple
A
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];
}
Azores answered 27/5, 2015 at 12:11 Comment(0)
G
3

Try

     myUILabel.intrinsicContentSize.width

Or

     myUILabel.intrinsicContentSize().width
Goldia answered 10/8, 2020 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.