Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS how to determine the size of UILabel dynamically

I'm trying to figure out a way to know what would be the size of the UILabel base on the string and font size to know how define the CGRect dimensions.

Here what I have until know:

UILabel *myLabel = [[UILabel alloc] init];
myLabel.font = [UIFont fontWithName:@"BentonSansComp-Medium" size:50.0];
myLabel.text = @"This is a string example"  

The problem is I don't have a list of the posible strings but and need to center the label and the string should not be chop (using the sting above example: "This is a str...."). any of you knows how can I determine the size of the UILabel base on the string and font size?

I'll really appreciate your help.

like image 422
user2924482 Avatar asked Feb 06 '14 18:02

user2924482


People also ask

How do you measure the height of a UILabel?

To summarize, you can calculate the height of a label by using its string and calling boundingRectWithSize . You must provide the font as an attribute, and include . usesLineFragmentOrigin for multi-line labels.

How do I change label height in Swift?

To give a dynamic height to an UIlabel in swift we can use the frame property of UILabel. We can create a frame using the CGRect which allows us to give different variables like x position, y position, width, and height.


1 Answers

just use

 UILabel *myLabel = [[UILabel alloc] init];
 myLabel.font = [UIFont fontWithName:@"BentonSansComp-Medium" size:50.0];
 myLabel.text = @"This is a string example" 
 [myLabel sizeToFit]; //it will resize the label to just the text is set
 CGRectMake size = myLabel.frame; // u will get the frame of the label once is resized
 float height = size.size.height;  //to get the height of the label
 float width = size.size.width;  //to get the width of the label

hope it helps

Make sure evrytime you change the text u call the [myLabel sizeToFit]; method

like image 179
Calleth 'Zion' Avatar answered Sep 22 '22 05:09

Calleth 'Zion'