Reputation: 91
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.
Upvotes: 6
Views: 25785
Reputation: 11026
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.
Upvotes: 16
Reputation: 3519
I've found that when using sizeToFit with a UILabel, in InterfaceBuilder you need to change the Autoshrink property from 'Fixed Font Size' to 'Minimum Font Size'. I usually then set its value to 0.5 to be sure its working properly.
Upvotes: 0
Reputation: 701
just make sure you increase the number of lines of the label. Instead of
questionLable.numberOfLines = 0;
make use of
questionLable.numberOfLines = 4;
As it will force the system to compute the smallest width possible for 4 lines.
You can achieve this via the Xib file too..
Upvotes: -1
Reputation: 2530
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.
Upvotes: 2
Reputation: 701
i googled d above problem and came across some info that sizeToFit seems to be a bug and it has been reported to apple already. So as a 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];
Upvotes: 0