2

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

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

    } while (fontSize > minFontSize);
}

alt text

Satyam
  • 15,493
  • 31
  • 131
  • 244

1 Answers1

2

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.

Jonathan.
  • 53,997
  • 54
  • 186
  • 290