【问题标题】:How to obtain adjusted font size from UILabel when adjustsFontSizeToFitWidth is YES in iOS 7?iOS 7中adjustsFontSizeToFitWidth为YES时如何从UILabel获取调整后的字体大小?
【发布时间】:2013-10-12 09:22:36
【问题描述】:

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

现在 iOS 7 弃用了所有以前有效的方法,所有关于 SO 的问题都建议使用这些弃用的方法。

只要得到 SO 的允许,我就会提出这个问题。请不要关闭。

【问题讨论】:

标签: ios nsstring uikit uilabel textkit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      【解决方案4】:

      您可以使用这行代码获得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;
      

      试试这个。

      【讨论】:

      • 在 iOS 8 上,float size = lblObj.font.pointSize 给了我请求的字体大小,而不是实际显示的字体大小。
      猜你喜欢
      • 2016-01-04
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2011-03-18
      相关资源
      最近更新 更多