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

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

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

Tags:

Ios

Uilabel

Swift