【问题标题】:How can I make text in a UILabel shrink font size如何使 UILabel 中的文本缩小字体大小
【发布时间】:2011-02-10 18:14:16
【问题描述】:

如果 UILabel 包含太多文本,我该如何设置标签以缩小字体大小?

这是我设置 UILabel 的方式:

     descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 30, 130, 150)];
    [descriptionLabel setFont:[Utils getSystemFontWithSize:14]];
    [descriptionLabel setBackgroundColor:[UIColor clearColor]];
    [descriptionLabel setTextColor:[UIColor whiteColor]];
    descriptionLabel.numberOfLines = 1;
    [self addSubview:descriptionLabel];

【问题讨论】:

    标签: iphone objective-c cocoa-touch interface-builder


    【解决方案1】:
    descriptionLabel.adjustsFontSizeToFitWidth = YES;
    descriptionLabel.minimumFontSize = 10.0; //adjust to preference obviously
    

    以下示例在 iPhone Simulator 3.1.2 上进行了测试和验证:

    UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 200, 30)];
    
    descriptionLabel.font = [UIFont systemFontOfSize:14.0];
    descriptionLabel.minimumFontSize = 10.0;
    descriptionLabel.adjustsFontSizeToFitWidth = YES;
    descriptionLabel.numberOfLines = 1;
    descriptionLabel.text = @"supercalifragilisticexpialidocious even thought he sound of it is something quite attrocious";
    

    【讨论】:

    • 我已经添加了这些行,但它似乎不起作用。即使我将我的矩形指定为像 CGRectMake(200,30,10,10) 这样的小东西,也没有任何反应。
    • 我不确定您的 [Utils getSystemFontWithSize:] 究竟返回了什么……我正在编辑我的答案以包含一个我刚刚测试和验证的示例。
    • 从 iOS 6 开始,您现在应该使用 setMinimumScaleFactor 而不是 minimumFontSize
    • 非常感谢。这为我节省了很多工作和时间。 @prendio2
    【解决方案2】:

    要调整多行 UILabel 中的文本大小,您可以使用此辅助方法(基于 11 Pixel Studios 的 code):

    + (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize { 
     // use font from provided label so we don't lose color, style, etc
     UIFont *font = aLabel.font;
    
     // start with maxSize and keep reducing until it doesn't clip
     for(int i = maxSize; i >= minSize; i--) {
      font = [font fontWithSize:i];
      CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);
    
      // This step checks how tall the label would be with the desired font.
      CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
      if(labelSize.height <= aLabel.frame.size.height)
       break;
     }
     // Set the UILabel's font to the newly adjusted font.
     aLabel.font = font;
    }
    

    【讨论】:

    • 在你的for循环中,条件应该是i &gt;= minSize,而不是i &gt; 10
    【解决方案3】:

    【讨论】:

      【解决方案4】:

      如果您希望行数在需要时也增加,请使用 Steve N 的解决方案,if 语句如下:

      if(labelSize.height <= aLabel.frame.size.height)
      {
        aLabel.numberOfLines = labelSize.height / font.lineHeight;
      
        break;
      }
      

      【讨论】:

      • 或者只是将行数设置为0。
      猜你喜欢
      • 2018-02-08
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-02
      • 2016-11-03
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多