Snowman
Snowman

Reputation: 32061

Truncate an NSString to width

I'm trying to convert the code found here to a binary algorithm instead, since the linear method is terribly slow. I have a working implementation, but theres seems to be some thing I'm missing, since the results I'm getting are not precise (that is, if I add or subtract 20 or so pixels from the width, I get the same truncated string..it should be a little more accurate and have a closer cut):

-(NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont*)font addQuotes:(BOOL)addQuotes
{
    int min = 0, max = self.length, mid;
    while (min < max) {
        mid = (min+max)/2;

        NSString *currentString = [self substringWithRange:NSMakeRange(min, mid - min)];
        CGSize currentSize = [currentString sizeWithFont:font];

        if (currentSize.width < width){
            min = mid + 1;
        } else if (currentSize.width > width) {
            max = mid - 1;
        } else {
            min = mid;
            break;
        }
    }
    return [self substringWithRange:NSMakeRange(0, min)];
}

Can anyone see off the bat what could be wrong with that? (This is a category method, so self is an NSString.

Upvotes: 5

Views: 3030

Answers (1)

jscs
jscs

Reputation: 64002

I'm pretty sure this line is wrong:

[self substringWithRange:NSMakeRange(min, mid - min)];

This means that every pass, you're only examining the size of the string from min to mid -- that's not the string that you're going to end up displaying, though, because min is marching up the string as you search. You should be always be testing starting from the beginning of the string:

[self substringWithRange:NSMakeRange(0, mid)];

which is what you're going to return when your search is done.

Upvotes: 2

Related Questions