OWolf
OWolf

Reputation: 5132

measure the amout of adjustsFontSizeToFitWidth for a UILabel or textField

UILabels and textFields can auto scale their fonts to fit the space of the view (as text accumulates for instance). Is there a way to measure the amount of the scale performed? As it seems, when auto scaling, the value of myLabel.font.pointsize or myTextField.font.pointSize remains the same regardless of the displayed scale of the text.

Upvotes: 3

Views: 1841

Answers (1)

Sebastian Celis
Sebastian Celis

Reputation: 12195

There is a method to do this in the UIKit additions for NSString:

- (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

So, if you are using a UILabel, you can use the following code:

CGFloat actualFontSize;
UILabel *label = [self label];
CGSize size = [[label text] sizeWithFont:[label font]
                             minFontSize:[label minimumFontSize]
                          actualFontSize:&actualFontSize
                                forWidth:[label bounds].size.width
                           lineBreakMode:[label lineBreakMode]];

At that point, size will contain the size of the drawn text and actualFontSize will be the actual size of the font that the label is using for drawing.

Upvotes: 6

Related Questions