Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel size to fit

Tags:

iphone

I have a problem involving UILabel's sizeToFit method:

UILabel *questionLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,0,320,320)];
questionLabel.lineBreakMode = UILineBreakModeWordWrap;
questionLabel.backgroundColor=[UIColor clearColor];
questionLabel.textAlignment=UITextAlignmentLeft;
questionLabel.textColor=[UIColor blackColor];
questionLabel.tag=1;
questionLabel.font=[UIFont systemFontOfSize:13];
questionLabel.numberOfLines = 0;
[questionLabel sizeToFit];
[myView addSubview:questionLabel];

I had written this code for displaying my data. But if I write: [questionLabel sizeToFit] my data does not display properly. If I remove [questionLabel sizeToFit] then it is displaying but it only shows half the data.

Thanks and Regards.

like image 917
fayaz Avatar asked Jun 08 '12 06:06

fayaz


People also ask

What is UILabel in Swift?

A view that displays one or more lines of informational text.

How do I change the width and height of a label 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. Let's create a label and add it as a subview to our view.

How do you change the text of a label in Swift?

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.


2 Answers

NSString *yourString = @"write your label text here";
CGSize s = [yourString sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
questionLabel.frame = CGRectMake(0, 0, s.width, s.height);

Check if it helps.

like image 103
Manish Agrawal Avatar answered Oct 02 '22 16:10

Manish Agrawal


I think it's best to use taus-iDeveloper answer to compute the size of a label.
I just want to say that the reason your code is not working is because you didn't set text to your UILabel so sizeToFit returns CGSizeZero (so it doesn't appear on screen). You have to set text before using sizeToFit.

like image 30
grandouassou Avatar answered Oct 02 '22 16:10

grandouassou