In order not to get confused with the method NSString sizeWithFontthat returns CGSize, I am looking for a method that returns NSString, limited to a specific one CGSize. The reason I want to do this is because when drawing text with, Core TextI can get the addition of ellipses (...) at the end of the line. I know that the method NSString drawInRectdoes this for me, but I use Core Text, but kCTLineBreakByTruncatingTailcut off the end of each line, not the end of the line.
There is this method that I found that cuts a string to a certain width, and it is not so difficult to change to make it work a CGSize, but the algorithm is incredibly slow for long lines and is practically not applicable. (It took more than 10 seconds to truncate a long line). There should be a more “computer science” / mathematical algorithm, a way to do it faster. Anyone bold enough to try to implement a faster implementation?
Edit: I was able to do this using a binary algorithm:
-(NSString*)getStringByTruncatingToSize:(CGSize)size string:(NSString*)string withFont:(UIFont*)font
{
int min = 0, max = string.length, mid;
while (min < max) {
mid = (min+max)/2;
NSString *currentString = [string substringWithRange:NSMakeRange(min, mid - min)];
CGSize currentSize = [currentString sizeWithFont:font constrainedToSize:CGSizeMake(size.width, MAXFLOAT)];
if (currentSize.height < size.height){
min = mid + 1;
} else if (currentSize.height > size.height) {
max = mid - 1;
} else {
break;
}
}
NSMutableString *finalString = [[string substringWithRange:NSMakeRange(0, min)] mutableCopy];
if(finalString.length < self.length)
[finalString replaceCharactersInRange:NSMakeRange(finalString.length - 3, 3) withString:@"..."];
return finalString;
}
The problem is that it sometimes cuts the string too short when it has room for spares. I think this is what the last condition comes to. How can I make sure it doesn't cut too much?