我有 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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)