Truncate NSString to Width

I am trying to convert the code found here to a binary algorithm, since the linear method is terribly slow. I have a working implementation, but it seems to me that something is missing, because the results that I get are not accurate (that is, if I add or subtract 20 pixels from the width, I get the same truncated string .. it should be a little more accurate and have a closer resolution):

-(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 with a bat what could be wrong with that? (This is a category method, therefore selfis NSString.

+5
source share
1 answer

I am sure this line is incorrect:

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

, , min mid - , , , min . , :

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

, .

+2

All Articles