在 .h 文件或 .h 和 .m 文件中向 UILabel 添加一个类别,其中 .h 文件将由使用它的代码导入:
@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
然后从代码中的多个位置像这样调用 UILabel 扩展:(假设您有一个名为 _instructions 的 UILabel 对象,并且您导入了实现 UILabelCategory 扩展的文件)
[_instructions adjustsFontSizeToFitWidthWithMinimumFontSize:[UILabel minimumLabelFontSize]];
或像这样:
[_instructions adjustsFontSizeToFitWidthWithMinimumFontSize:14];
注意:请记住,在 iOS 6 和之前的版本中,setMinimumFontSize 仅在您还将行数设置为 1 时才有效,如下所示:
[_instructions setNumberOfLines:1]; // on iOS6 and earlier the AdjustsFontSizeToFitWidth property is only effective if the numberOfLines is 1