sizeWithFont Returns a width 0

1k Views Asked by At

My ultimate goal is to vary the font size so that various words fit in the same rectangular area. I thought sizeWithFont would be a great method to use but I keep getting a width of 0 and I'm confused.

NSString *name = @"Test Word";
CGFloat fontSize = 32.0;
UIFont *font = [UIFont fontWithName:@"TimeNewRomanPSMT" size: fontSize]; 
CGSize sWidth = [name sizeWithFont:font 
             constrainedToSize:CGSizeMake(fontSize, CGFLOAT_MAX)
          lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"sWidth =  %3.1f; rec.width n= %3.1f ", sWidth.width, rec.width);

My plan is to loop through font sizes until the width fits but sWidth.width keeps returning 0.

Chris

2

There are 2 best solutions below

3
On

The font name is TimesNewRomanPSMT and no TimeNewRomanPSMT.

Notice the s after Times, a common error!

This web site is very helpful to validate the font names as well as listing and having an example of all fonts available in iOS:

http://iosfonts.com/

0
On

the first thing that you should suggest and check in this case - that your font is not nil. It can happen if you entered not correct font name