14
votes

I have a label that is set to adjustsFontSizeToFitWidth = YES and I need to get the actual displayed font size.

Now iOS 7 deprecated all methods that worked previously and all questions on SO suggest using these deprecated methods.

I will make this question a bounty as soon as I am allowed to by SO. Please do not close.

4
The problem is discussed here and has answers! stackoverflow.com/questions/2396715/…katleta3000
please check my answer at the bottom belowMd. Ibrahim Hassan

4 Answers

0
votes

UILabel displayed fontSize in case of using adjustsFontSizeToFitWidth in iOS 7

UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
label.text = @" Your Text goes here into this label";
label.adjustsFontSizeToFitWidth = YES;

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
// Get the theoretical font-size
[attrStr setAttributes:@{NSFontAttributeName:label.font} range:NSMakeRange(0, attrStr.length)];

NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = label.minimumScaleFactor;
[attrStr boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin context:context];
CGFloat theoreticalFontSize = label.font.pointSize * context.actualScaleFactor;

NSLog(@"theoreticalFontSize: %f",theoreticalFontSize);
NSLog(@"AttributedString Width: %f", [attrStr size].width);
double scaleFactor=label.frame.size.width/([attrStr size].width);
double displayedFontSize=theoreticalFontSize*scaleFactor;
NSLog(@"Actual displayed Font Size: %f",displayedFontSize);

// Verification of Result
double verification=(displayedFontSize * [attrStr length]);
NSLog(@"Should be equal to %0.5f: %0.5f ", [attrStr size].width/17.0, label.frame.size.width/displayedFontSize);
-1
votes

Try inserting [lblObj sizeToFit] just before requesting the font size

-2
votes

There's a readonly property that lets you do that. You can access it like this

nameLabel.adjustsFontSizeToFitWidth = YES;

//Make sure to use the line below AFTER the line above

float fontSize = nameLabel.font.xHeight;

This will give you the font size after it has been adjusted to fit width.

-2
votes

You can get the font size of UILabel text using these line of code.

UILabel *lblObj = [[UILabel alloc]init];
lblObj.text = @" Your Text";
lblObj.adjustsFontSizeToFitWidth = YES;
float size = lblObj.font.pointSize; //Here You will get the actual size of the text.
float lineHeight = lblObj.font.lineHeight;

Try this one.