Resulting lines of UILabel with UILineBreakModeWordWrap

Nick picture Nick · Nov 2, 2010 · Viewed 15k times · Source

I have a UILabel whose size is calculated with sizeWithFont: method. The line break mode is set to UILineBreakModeWordWrap (same flag is used when calculating the size with sizeWithFont:)...

Everything works great, label is properly sized and displays my text as required.

Now I need to know the lines that are used to display the label (or the lines that are generated when sizeWithFont: is used). I could technically write my own implementation of line breaking based on spaces/caret returns, but then it's not going to be guaranteed the same way as Apple's implementation and hence the resulting lines will not be the ones that are used to calculate the size of text, nevermind the fact of reinventing the wheel.

Ideally, I would pass my string, specify the width and line break mode and receive an array of strings representing the visual lines of text.

Any ideas how to make this happen in the most elegant way?

Answer

Adolfo picture Adolfo · Nov 13, 2010

To calculate the number of lines that a UILabel has after wrapping it's text you will need to find the leading (line height) of your UILabel's font (label.font.leading) and then divide the height of your multi-line UILabel by the height of each line to yield the number of lines.

Here's an example:

- (void)viewDidLoad {

    [super viewDidLoad];

    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    label.numberOfLines = 0;
    label.lineBreakMode = UILineBreakModeWordWrap;  
    label.text = @"Some really really long string that will cause the label's text to wrap and wrap and wrap around. Some really really long string that will cause the label's text to wrap and wrap and wrap around.";

    CGRect frame = label.frame;
    frame.size.width = 150.0f;
    frame.size = [label sizeThatFits:frame.size];
    label.frame = frame;

    CGFloat lineHeight = label.font.leading;
    NSUInteger linesInLabel = floor(frame.size.height/lineHeight);
    NSLog(@"Number of lines in label: %i", linesInLabel);

    [self.view addSubview:label];

}

Or, you could do it in two lines:

[label sizeToFit];
int numLines = (int)(label.frame.size.height/label.font.leading);