Add a category to UILabel like this in a .h file or in .h and .m files where the .h file will be imported by the code that uses it:
@interface UILabel (UILabelCategory)
+ (CGFloat)minimumLabelFontSize;
- (void)adjustsFontSizeToFitWidthWithMinimumFontSize:(CGFloat)fontSize;
@end
@implementation UILabel (UILabelCategory)
+ (CGFloat)minimumLabelFontSize // class method that returns a default minimum font size
{
return 11;
}
- (void)adjustsFontSizeToFitWidthWithMinimumFontSize:(CGFloat)fontSize
{
if ([self respondsToSelector: @selector(setMinimumScaleFactor:)])
{
CGFloat currentFontSize = self.font.pointSize == 0 ? [UIFont labelFontSize] : self.font.pointSize;
[self setMinimumScaleFactor:fontSize / currentFontSize];
}
else
{
[self setMinimumFontSize:fontSize]; // deprecated, only use on iOS's that don't support setMinimumScaleFactor
}
[self setAdjustsFontSizeToFitWidth:YES];
}
@end
And then call the UILabel extension like this from multiple places in your code:
(assuming that you have a UILabel object called _instructions and that you import the file that implements the UILabelCategory extension)
[_instructions adjustsFontSizeToFitWidthWithMinimumFontSize:[UILabel minimumLabelFontSize]];
or like this:
[_instructions adjustsFontSizeToFitWidthWithMinimumFontSize:14];
Note: remember that on iOS 6 and prior the setMinimumFontSize only works if you also set the number of lines to 1 like this:
[_instructions setNumberOfLines:1]; // on iOS6 and earlier the AdjustsFontSizeToFitWidth property is only effective if the numberOfLines is 1