Adapting Binary Search

It’s great to use classic algorithms to solve problems at hand. Take this problem of ellipsis: For a given text. Fit the maximum number of words that fits in the given size, append “… More” if there was truncation. No, NSLineBreakModeTailTruncation will not work. We need different text. The näive solution would simply to cut a word one-by-one until it fits with a custom ellipsis text: @implementation NSString (CustomEllipsis) - (NSString *)textThatFitsSize:(CGSize)size ellipsisText:(NSString *)text { CGSize infiniteSize = CGSizeMake(size.width, INFINITY); CGSize fullSize = [text boundingRectWithSize:infiniteSize options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin context:nil].size; // if text fits if (fullSize.height <= size.height) { return text; } NSString *finalString = nil; // if text doesn't fit NSMutableArray *words = [[text componentsSeparatedByString:@" "] mutableCopy]; while (fullSize.height > size.height) { [words removeLastObject]; finalString = [words componentsJoinByString:@" "]; finalString = [finalString stringByAppendString:@"... MORE"]; fullSize = [modifiedString boundingRectWithSize:infiniteSize options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin context:nil].size; } return finalString; } @end Run that in a table cell and you’ve got performance problems! ...

July 25, 2014 · 2 min