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.
To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.
text = text; label. numberOfLines = 0; [label sizeToFit]; return cell; Also use NSString 's sizeWithFont:constrainedToSize:lineBreakMode: method to compute the text's height. Show activity on this post.
Try myUILabel.intrinsicContentSize()
. Make sure you set your font first, of course.
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.width
Or
myUILabel.intrinsicContentSize().width
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With