开发者

iPad/iPhone - Set the label size that fits in the given rect

In my ipad application, i've a lable that occupies whole view. I want to dynamically calculate the size of the label that fits in the whole rect. But I want to maintain the word wrap. In my XIB, I added a label and set it mode to word wrap mode.

See the image attached. What I want is to show the label with word wrap. Can some one help me to find the problem?

The following is the code that I'm using: (In one of the answers in these forums, I found the following code:)

-(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 )
   br开发者_如何学Ceak;

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

    } while (fontSize > minFontSize);
}

iPad/iPhone - Set the label size that fits in the given rect


So you trying to get the text to be wordwrapped, but with the maximum possible size? In that case do:

//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];

And that should be all you need to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜