18

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?

Nick
  • 2,626
  • 1
  • 26
  • 29

5 Answers5

38

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);
Adolfo
  • 4,969
  • 4
  • 26
  • 28
  • ah, this is very smart. simpler than my solution, for sure! – TomSwift Nov 19 '10 at 17:04
  • 3
    Note that **"leading"** is pronounced "ledding". (Exactly as in "Led Zepplin", NOT as in "follow the leader".) It simply means the metal, led (ie, the atomic substance Pb) - the word comes from the early days of typography when you literally put led strips between the letters to create the, well, ledding. – Fattie Nov 21 '13 at 08:58
  • Thanks .... [label sizeToFit]; int numLines = (int)(label.frame.size.height/label.font.leading); worked for me – Swapnil Godambe Dec 20 '13 at 05:37
24

I don't think there is any silver bullet for this.

Here is a category method that seems to work for the few basic test cases I threw at it. No guarantees it won't break with something complex!

The way it works is to move through the string testing to see if a range of words fits in the width of the label. When it calculates that the current range is too wide it records the last-fitting range as a line.

I don't claim this is efficient. A better way may just to be to implement your own UILabel...

@interface UILabel (Extensions)

- (NSArray*) lines;

@end

@implementation UILabel (Extensions)

- (NSArray*) lines
{
    if ( self.lineBreakMode != UILineBreakModeWordWrap )
    {
        return nil;
    }

    NSMutableArray* lines = [NSMutableArray arrayWithCapacity:10];

    NSCharacterSet* wordSeparators = [NSCharacterSet whitespaceAndNewlineCharacterSet];

    NSString* currentLine = self.text;
    int textLength = [self.text length];

    NSRange rCurrentLine = NSMakeRange(0, textLength);
    NSRange rWhitespace = NSMakeRange(0,0);
    NSRange rRemainingText = NSMakeRange(0, textLength);
    BOOL done = NO;
    while ( !done )
    {
        // determine the next whitespace word separator position
        rWhitespace.location = rWhitespace.location + rWhitespace.length;
        rWhitespace.length = textLength - rWhitespace.location;
        rWhitespace = [self.text rangeOfCharacterFromSet: wordSeparators options: NSCaseInsensitiveSearch range: rWhitespace];
        if ( rWhitespace.location == NSNotFound )
        {
            rWhitespace.location = textLength;
            done = YES;
        }

        NSRange rTest = NSMakeRange(rRemainingText.location, rWhitespace.location-rRemainingText.location);

        NSString* textTest = [self.text substringWithRange: rTest];

        CGSize sizeTest = [textTest sizeWithFont: self.font forWidth: 1024.0 lineBreakMode: UILineBreakModeWordWrap];
        if ( sizeTest.width > self.bounds.size.width )
        {
            [lines addObject: [currentLine stringByTrimmingCharactersInSet:wordSeparators]];
            rRemainingText.location = rCurrentLine.location + rCurrentLine.length;
            rRemainingText.length = textLength-rRemainingText.location;
            continue;
        }

        rCurrentLine = rTest;
        currentLine = textTest;
    }

    [lines addObject: [currentLine stringByTrimmingCharactersInSet:wordSeparators]];

    return lines;
}

@end

use like this:

NSArray* lines = [_theLabel lines];

int count = [lines count];
TomSwift
  • 39,369
  • 12
  • 121
  • 149
  • 1
    Thanks TomSwift for your input... This sort of works for some cases, but it definitely gave me a big boost, I'm working on a more bullet proof solution based on your code. Thanks again! – Nick Nov 15 '10 at 23:01
  • Nice solution TomSwift. But it doesn't work for me, it's always the text on one line though int count sometimes are 9, 10 or 20. My code: self.labelDescription.text = event.description; self.labelDescription.lineBreakMode = UILineBreakModeWordWrap; self.labelDescription.font = [UIFont fontWithName:@"Helvetica" size:13.0]; NSArray* lines = [self.labelDescription lines]; int count = [lines count]; self.labelDescription.numberOfLines = count; – Fernando Redondo Feb 08 '11 at 14:55
  • 1
    Nice solution but there was an issue for me the last two lines were always the same. I amended that by adding currentLine = [self.text substringWithRange: rRemainingText]; before the continue; – simongking May 13 '12 at 16:57
11

Just call below method and pass either UILabel or UITextView:

-(NSInteger)getNumberOfLinesInLabelOrTextView:(id)obj
{
    NSInteger lineCount = 0;
    if([obj isKindOfClass:[UILabel class]])
    {
        UILabel *label = (UILabel *)obj;

       // This method is deprecated in iOS 7.0 or later 
       // CGSize requiredSize = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size lineBreakMode:label.lineBreakMode]; 

        CGSize requiredSize = [label.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(label.frame), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:nil].size;

        int charSize = label.font.leading;
        int rHeight = requiredSize.height;

        lineCount = rHeight/charSize;
    }
    else if ([obj isKindOfClass:[UITextView class]])
    {
        UITextView *textView = (UITextView *)obj;
        lineCount = textView.contentSize.height / textView.font.leading;
    }

    return lineCount;
}

Now call this method:-

NSLog(@"%d",[self getNumberOfLinesInLabelOrTextView:label]);
NSLog(@"%d",[self getNumberOfLinesInLabelOrTextView:textView]);

UPDATED: SWIFT CODE

func getNumberOfLinesInLabelOrTextView(obj:AnyObject) -> NSInteger {

    var lineCount: NSInteger = 0
    if (obj.isKindOfClass(UILabel)) {

        let label: UILabel = obj as! UILabel
        let requiredSize: CGSize = (label.text)!.boundingRectWithSize(CGSizeMake(CGRectGetWidth(label.frame), CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: label.font], context: nil).size
        let charSize: CGFloat = label.font.leading
        let rHeight: CGFloat = requiredSize.height
        lineCount = (NSInteger)(rHeight/charSize)
    }
    else if (obj.isKindOfClass(UITextView)){

        let textView: UITextView = obj as! UITextView
        lineCount = (NSInteger)(textView.contentSize.height / textView.font.leading)
    }

    return lineCount
}

Now call this method:-

println("%d \(self.getNumberOfLinesInLabelOrTextView(textView))")
println("%d \(self.getNumberOfLinesInLabelOrTextView(label))")

Note: leading - use lineHeight. does not return actual leading. will be formally deprecated in future.

TheTiger
  • 13,264
  • 3
  • 57
  • 82
  • This worked well but when I update xcode to 7 it's show "exc_arithmetic code=exc_i386_div" error on line lineCount = rHeight/charSize; . So I did lineCount = rHeight/1; now it's working. If I wrong guide me correct one :) – Mathi Arasan Sep 22 '15 at 06:43
0

for Xcode 7 and up TheTiger's answer needs an update commented on the code below :

-(NSInteger)getNumberOfLinesInLabelOrTextView:(id)obj
{
    NSInteger lineCount = 0;
    if([obj isKindOfClass:[UILabel class]])
    {
        UILabel *label = (UILabel *)obj;
        CGSize requiredSize = [label.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(label.frame), CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:nil].size;

        int charSize = label.font.leading;
        // now listen , you need to set the text or label with only 1 
        // then nslog(@"%d",charSize);
        // then change the line int charSize = label.font.leading; into 
        // int charSize = the printed value in case of 1 line
        int rHeight = requiredSize.height;

        lineCount = rHeight/charSize;
    }
    else if ([obj isKindOfClass:[UITextView class]])
    {
        UITextView *textView = (UITextView *)obj;
        lineCount = textView.contentSize.height / textView.font.leading;
    }

    return lineCount;
}

this will only work if you are using same font and size , it's not a smart move but it helped me and i wanted to share it as the current solution i know

Mostafa Sultan
  • 2,268
  • 2
  • 20
  • 36
0

Updated for Swift 3

To calculate the number of lines that UILabel has, after wrapping its text, you need to divide the height of your multi-line UILabel by the height of each line (ascender).

When trying Adolfo's answer, for some reason, label.font.leading returned 0.0, so I used label.font.ascender, which returns the height from the baseline to the top of the UILabel's frame. See picture below.

enter image description here

//Makes label go to another line if necessary
label.numberOfLines = 0 //Set num of lines to infinity
label.lineBreakMode = .byWordWrapping
label.sizeToFit()
let numLines = Int(label.frame.size.height/label.font.ascender)
14wml
  • 4,048
  • 11
  • 49
  • 97