UILabel size to fit

I have a problem with the UILabel 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 wrote this code to display my data. But if I write: [questionLabel sizeToFit] my data is not displayed correctly. If I delete [questionLabel sizeToFit] , then it will be displayed, but only half of the data will be displayed.

Thanks and respect.

+6
source share
6 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 this helps.

+16
source

I think it is best to use the taus-iDeveloper answer to calculate the label size.
I just want to say that the reason your code doesn’t work is because you did not set the text in your UILabel, so sizeToFit returns CGSizeZero (therefore it does not appear on the screen). You must set the text before using sizeToFit.

+2
source

I found that if AutoLayout is enabled, then the size is not suitable for work

+2
source

i googled d above the problem and stumbled upon some information that sizeToFit seems to be an error, and this is already reported in apple. Since the workaround u can use this code:

 NSString * myText = [NSString stringWithString:@"some text"]; CGFloat constrainedSize = 265.0f; UIFont * myFont = [UIFont fontWithName:@"Arial" size:19]; CGSize textSize = [myText sizeWithFont: myFont constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height); UILabel *label = [[UILabel alloc] initWithFrame:labelFrame]; [label setFont:myFont]; [label setText:myText]; 
0
source

I found that when using sizeToFit with UILabel in InterfaceBuilder you need to change the Autoshrink property from "Fixed Font Size" to "Minimum Font Size". I usually set its value to 0.5 to make sure that it works correctly.

0
source

just make sure you increase the number of label lines. Instead

questionLable.numberOfLines = 0; use

questionLable.numberOfLines = 4; As this will cause the system to calculate the smallest width possible for 4 lines.

You can achieve this with the Xib file ..

-1
source

Source: https://habr.com/ru/post/917585/


All Articles