Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel get the displayed font size when adjustsFontSizeToFitWidth is YES

Tags:

ios

uikit

uilabel

I have a UILabel with adjustsFontSizeToFitWidth set to YES and as expected it shrinks the font displayed on screen when the text is too large to be drawn at the size of the font property.

I have already interrogated the font property but this remains the same as it was when originally set on the label, and UILabel doesn't seem to have any other properties that could be of use.

Is there a way to find out what the size of the shrunken text drawn by the label is?

EDIT: Not a duplicate as suggested because sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: was deprecated in iOS7

like image 705
Stephen Groom Avatar asked Oct 07 '15 10:10

Stephen Groom


1 Answers

Turns out it is a bit more complex since iOS 7 deprecated the useful sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:, as used in the suggested duplicate.

We now have to use NSAttributedString instead.

Create an NSAttributedString from the string to be / that is set on the label. Setting the entire attributed string's font to whatever the label's font is.

NSDictionary *attributes = @{NSFontAttributeName : self.label.font};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:text
                                                                       attributes:attributes];

Then, create a NSStringDrawingContext object, configured to use the minimum scale factor of the label. This will be used to assist in the calculation of the actual font size.

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
context.minimumScaleFactor = self.label.minimumScaleFactor;

We can then use the NSAttributedString method to calculate the bounding rect, and further configure the NSStringDrawingContext:

[attributedString boundingRectWithSize:self.label.bounds.size
                               options:NSStringDrawingUsesLineFragmentOrigin
                               context:context];

This will make a drawing pass and the context will be updated to include the scale factor that was used in order to draw the text in the space available (the label's size).

Getting the actual font size is then as simple as:

CGFloat actualFontSize = self.label.font.pointSize * context.actualScaleFactor;
like image 77
Steve Wilford Avatar answered Sep 19 '22 10:09

Steve Wilford