如何在iOS 7中获取UILabel的调整字体大小,当adjustsFontSizeToFitWidth为YES时?

14
我有一个标签,设置为adjustsFontSizeToFitWidth = YES,我需要获取实际显示的字体大小。
现在iOS 7已弃用了之前可用的所有方法,而所有关于此问题的问题都建议使用这些已弃用的方法。
一旦允许,我将为此问题设置悬赏,请勿关闭。

这里讨论了一个问题,并且有答案! https://dev59.com/aXE95IYBdhLWcg3wPbd7 - katleta3000
https://dev59.com/914c5IYBdhLWcg3wHXNS#32567240 - evya
请检查我下面的答案 - Md. Ibrahim Hassan
4个回答

0

iOS 7中使用adjustsFontSizeToFitWidth时,UILabel显示的字体大小

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);

-1
尝试在请求字体大小之前插入[lblObj sizeToFit]

-2

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

nameLabel.adjustsFontSizeToFitWidth = YES;

//Make sure to use the line below AFTER the line above

float fontSize = nameLabel.font.xHeight;

这将会给你适应宽度后的字体大小。

-1 这个答案是不正确的。请看这篇博客:http://www.cocoanetics.com/2010/02/understanding-uifont/ ——UIFont的x高度和其他所有指标仍然只反映原始字体大小。 - daveMac

-2

您可以使用以下代码获取 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;

试试这个。


5
在 iOS 8 上,float size = lblObj.font.pointSize 给出的是所请求的字体大小,而不是实际显示的字体大小。 - Ian Howson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接