'How to get the correct width of a UILabel after the text has been set?

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.



Solution 1:[1]

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

Solution 2:[2]

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];
}

Solution 3:[3]

Try

     myUILabel.intrinsicContentSize.width

Or

     myUILabel.intrinsicContentSize().width

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jolly Roger
Solution 2 Sanjay Mohnani
Solution 3