不幸的是,如果你记录 labelLong 的字体,它仍然显示为默认大小 17,所以你不能用简单的方法做到这一点。我发现这样做的一种方法是从原始字体开始,并循环通过较小的字体大小,直到文本的边界矩形宽度小于标签文本矩形的宽度(从 textRectForBounds:limitedToNumberOfLines 获得:)。这段代码对我有用,但我还没有彻底测试过。我每次通过循环将字体大小调整 0.1 以获得合理准确的答案。
@interface ViewController ()
@property (strong,nonatomic) UILabel *labelLong;
@property (strong,nonatomic) UILabel *labelShort;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.labelLong = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, 50, 50)];
self.labelLong.text = @"Very text";
self.labelLong.adjustsFontSizeToFitWidth = YES;
[self.view addSubview:self.labelLong];
self.labelShort = [[UILabel alloc] initWithFrame:CGRectMake(20, 70, 50, 50)];
self.labelShort.text = @"Very";
[self.view addSubview:self.labelShort];
[self updateFont];
}
-(void)updateFont {
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
ctx.minimumScaleFactor = 1.0;
UIFont *startingFont = self.labelLong.font;
NSString *fontName = startingFont.fontName;
CGFloat startingSize = startingFont.pointSize;
for (float i=startingSize*10; i>1; i--) {
UIFont *font = [UIFont fontWithName:fontName size:i/10];
CGRect textRect = [self.labelLong.text boundingRectWithSize:self.labelLong.frame.size options:NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:font} context:ctx];
if (textRect.size.width < [self.labelLong textRectForBounds:self.labelLong.bounds limitedToNumberOfLines:1].size.width) {
NSLog(@"Font size is: %f", i/10);
NSLog(@"Font rect is: %@",NSStringFromCGRect(textRect));
self.labelShort.font = [UIFont fontWithName:fontName size:i/10];
break;
}
}
}