Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

uilabel

swift

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.

like image 590
Megaetron Avatar asked May 27 '15 12:05

Megaetron


People also ask

How do you change the width of a UILabel?

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.

How do you text the height of UILabel?

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.


3 Answers

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

like image 181
Jolly Roger Avatar answered Sep 30 '22 19:09

Jolly Roger


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]; } 
like image 39
Sanjay Mohnani Avatar answered Sep 30 '22 19:09

Sanjay Mohnani


Try

     myUILabel.intrinsicContentSize.width

Or

     myUILabel.intrinsicContentSize().width
like image 39
Grenoblois Avatar answered Sep 30 '22 20:09

Grenoblois