Search code examples
iphonehtmlwebviewcrop

Crop last sentence from html string if it does not fit webView (iphone)


I have an array of texts that have bold parts in them. There is no rule where this bold word or sentence is, so i am using webView to display html string with bold tags where necessary. Now my webViews do not scroll anywhere and sometimes the text does not fit in them.

So here is my question:

I want to crop text so, that it would fit my webView and the cropping wouldn't be in the middle of sentence, but instead would crop out whole sentence if it doesn't fit. So in the end, the text should end with final sentence that fits.


Solution

  • What I did was strip html tags from the html sentence, calculate the height that the text takes up then remove last part of text, separated with "." (dot) if it exceeds required height.

    Here is the code to do this.

    NSString *returnedString = [[[NSString alloc] initWithString:htmlText] autorelease];

    CGSize a = [[returnedString stripHtml] sizeWithFont:font constrainedToSize:CGSizeMake(sizeToFit.width, 999)];
    
    
    NSMutableArray *sentences = [[NSMutableArray alloc] initWithArray:[returnedString componentsSeparatedByString:@"."]];
    
    while (a.height > sizeToFit.height) {
        
        _lastTextExceededLimits = NO;
        
        if (sentences.count > 1) {
            // -2 because last sentence is not deletable and contains html tags
            NSString *sentence2 = [sentences objectAtIndex:(sentences.count - 2)];
            
            NSString *stringToReplace = [NSString stringWithFormat:@"%@%@",sentence2, @"."];
            returnedString = [returnedString stringByReplacingOccurrencesOfString:stringToReplace  withString:@""];
            
            [sentences removeLastObject];
        } else
            returnedString = [returnedString stringByReplacingOccurrencesOfString:[sentences lastObject] withString:@""];
        
        a = [[returnedString stripHtml] sizeWithFont:font constrainedToSize:CGSizeMake(sizeToFit.width, CGFLOAT_MAX)];
        
        
    }
    [sentences release];
    
    return returnedString;