如何为多个标签设置相同的字体比例,具体取决于哪一个是自动收缩?

我有4个标签视图,其中一个应该显示大数值并设置为自动收缩。

我的要求是在自动调整以适应其内容之后,将此标签设置为与其他标签相同的字体缩放或大小,以便文本内容在整个过程中看起来均匀。

设置最小比例因子对其他标签没有帮助,因为它们具有帧限制内的内容。

没有办法直接执行此操作,因为查询文本缩小以适合的标签字体仍然显示原始字体大小。 您必须通过迭代越来越小的字体大小来执行此操作,直到找到适合您标签的大小,然后使用该字体大小来调整其他标签。 在下面的示例中,labelLong是文本可以缩小的文本,labelShort是其文本不需要缩小的文本。

-(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--) { // multiply by 10 so we can adjust font by tenths of a point with each iteration 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); self.labelShort.font = [UIFont fontWithName:fontName size:i/10]; break; } } }