Michael Leveton
Michael Leveton

Reputation: 333

iOS sizeToFit not showing text

I'm creating these labels for a Storyboard view. I have autolayout set to OFF and I'm setting the numberoflines to 0 but the text is only displayed if I comment out sizeToFit. Then, of course, the text gets cut off when its height is greater than 40.

- (void)viewDidLoad
{

[super viewDidLoad];
first = @"This text fits in the label";
second = @"This large text is too large for the label but because the words are normal sized, shows the more button correctly at the bottom right";
third = @"Doesn't show the more button correctly because WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW";

firstlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 57, 295, 40)];
secondlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 152, 295, 40)];
thirdlbl = [[UILabel alloc]initWithFrame:CGRectMake(13, 225, 295, 40)];

[firstlbl setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14]];
[secondlbl setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14]];
[thirdlbl setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14]];

firstlbl.lineBreakMode = NSLineBreakByWordWrapping;
secondlbl.lineBreakMode = NSLineBreakByWordWrapping;
thirdlbl.lineBreakMode = NSLineBreakByWordWrapping;

firstlbl.numberOfLines = 0;
secondlbl.numberOfLines = 0;
thirdlbl.numberOfLines = 0;
[firstlbl sizeToFit];
[secondlbl sizeToFit];
[thirdlbl sizeToFit];

[firstlbl setText:first];
[secondlbl setText:second];
[thirdlbl setText:third];

[self.view addSubview:firstlbl];
[self.view addSubview:secondlbl];
[self.view addSubview:thirdlbl];

}

Upvotes: 0

Views: 221

Answers (1)

Ian Henry
Ian Henry

Reputation: 22403

You're calling sizeToFit before you set the text, so it's sizing down to CGRectZero. Switch those calls and it'll work.

sizeToFit doesn't mean "automatically adjust your size to fit your content," it means "update your size right now to fit your content." Subsequent updates to the text won't change the frame.

If you want the former behavior, so that it automatically sizes itself to its content, autolayout is probably the easiest road to take.

Upvotes: 1

Related Questions