如何在iOS 7中调整字体大小到适合宽度时从UILabel获取调整后的字体大小是YES



>我有一个设置为adjustsFontSizeToFitWidth = YES的标签,我需要获取实际显示的字体大小。

现在,iOS 7弃用了以前工作的所有方法,SO上的所有问题都建议使用这些不推荐使用的方法。

一旦SO允许,我将立即将这个问题作为赏金。请不要关闭。

UILabel在iOS 7中使用adjustsFontSizeToFitWidth的情况下显示fontSize

UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
label.text = @" Your Text goes here into this label";
label.adjustsFontSizeToFitWidth = YES;
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
// Get the theoretical font-size
[attrStr setAttributes:@{NSFontAttributeName:label.font} range:NSMakeRange(0, attrStr.length)];
NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = label.minimumScaleFactor;
[attrStr boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin context:context];
CGFloat theoreticalFontSize = label.font.pointSize * context.actualScaleFactor;
NSLog(@"theoreticalFontSize: %f",theoreticalFontSize);
NSLog(@"AttributedString Width: %f", [attrStr size].width);
double scaleFactor=label.frame.size.width/([attrStr size].width);
double displayedFontSize=theoreticalFontSize*scaleFactor;
NSLog(@"Actual displayed Font Size: %f",displayedFontSize);
// Verification of Result
double verification=(displayedFontSize * [attrStr length]);
NSLog(@"Should be equal to %0.5f: %0.5f ", [attrStr size].width/17.0, label.frame.size.width/displayedFontSize);
尝试在

请求字体大小之前插入[lblObj sizeToFit]

有一个只读属性可以让你做到这一点。你可以像这样访问它

nameLabel.adjustsFontSizeToFitWidth = YES;
//Make sure to use the line below AFTER the line above
float fontSize = nameLabel.font.xHeight;

这将在调整字体大小以适应宽度后为您提供字体大小。

您可以使用

这些代码行获取UILabel文本的字体大小。

UILabel *lblObj = [[UILabel alloc]init];
lblObj.text = @" Your Text";
lblObj.adjustsFontSizeToFitWidth = YES;
float size = lblObj.font.pointSize; //Here You will get the actual size of the text.
float lineHeight = lblObj.font.lineHeight;

试试这个。

最新更新