views:

598

answers:

2

In UILabel there's functionality to truncate labels using different truncation techniques (UILineBreakMode). In NSString UIKit Additions there is a similar functionality for drawing strings.

However, I found no way to access the actual truncated string. Is there any other way to get a truncated string based on the (graphical) width for a given font?

I'd like to have a category on NSString with this method:

-(NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

+1  A: 

One option is trying different sizes by looping until you get the right width. I.e. start with the full string, if that's wider than what you need, replace the last two characters with an ellipsis character. Loop until it's narrow enough.

If you think you'll be working with long strings, you can binary search your way towards the truncation point to make it a bit faster.

uliwitness
Thanks Uli, good idea. Works like a charm. See the code in the other comment.
Ortwin Gentz
+3  A: 
- (NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode {
    NSMutableString *resultString = [[self mutableCopy] autorelease];
    NSRange range = {resultString.length-1, 1};

    while ([resultString sizeWithFont:font forWidth:FLT_MAX lineBreakMode:lineBreakMode].width > width) {
        // delete the last character
        [resultString deleteCharactersInRange:range];
        range.location--;
        // replace the last but one character with an ellipsis
        [resultString replaceCharactersInRange:range withString:truncateReplacementString];
    }
    return resultString;
}
Ortwin Gentz