【问题标题】:iPad/iPhone - Set the label size that fits in the given rectiPad/iPhone - 设置适合给定矩形的标签大小
【发布时间】:2011-01-22 12:23:24
【问题描述】:

在我的 ipad 应用程序中,我有一个占据整个视图的标签。我想动态计算适合整个矩形的标签大小。但我想保持自动换行。 在我的 XIB 中,我添加了一个标签并将其模式设置为自动换行模式。

见附图。我想要的是用自动换行显示标签。谁能帮我找出问题所在?

以下是我正在使用的代码: (在这些论坛的一个答案中,我找到了以下代码:)

-(void)sizeLabel:(UILabel*)label toRect:(CGRect)labelRect withFont:(NSString*)fontName {

    // Set the frame of the label to the targeted rectangle
    label.frame = labelRect;

    // Try all font sizes from largest to smallest font size
    int fontSize = 300;
    int minFontSize = 5;

    // Fit label width wize
    CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);

    do {
  // Set current font size
  label.font = [UIFont fontWithName:fontName size:fontSize];

  // Find label size for current font size
  CGSize labelSize = [[label text] sizeWithFont:label.font
      constrainedToSize:constraintSize
      lineBreakMode:UILineBreakModeWordWrap];

  // Done, if created label is within target size
  if( labelSize.height <= label.frame.size.height )
   break;

  // Decrease the font size and try again
  fontSize -= 2;

    } while (fontSize > minFontSize);
}

【问题讨论】:

    标签: iphone ipad resize uilabel


    【解决方案1】:

    所以你试图让文本被自动换行,但尽可能大? 在这种情况下:

    //With the line break mode set to wordwrap and number of lines set to 1.
    [label adjustsFontSizeToFitWidth:YES];
    //set max font
    label.font = [UIFont fontWithName:fontName 300];
    [label setMinimumFontSize:5];
    

    这就是你需要做的所有事情。

    【讨论】:

    • 第一行代码应该是[label setAdjustsFontSizeToFitWidth:YES];
    猜你喜欢
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2014-07-02
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多