Search code examples
iphonecocoa-touchiphone-sdk-3.0nsstringuilabel

Resulting lines of UILabel with UILineBreakModeWordWrap


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?


Solution

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