Skip to content

Instantly share code, notes, and snippets.

@Wevah
Last active December 29, 2015 14:29
Show Gist options
  • Save Wevah/7684270 to your computer and use it in GitHub Desktop.
Save Wevah/7684270 to your computer and use it in GitHub Desktop.
Truncate a string, with an ellipsis in the center, to a max point width, without splitting composed character sequences (grapheme clusters).
- (NSString *)stringByInsertingCenterEllipsisWithMaxWidth:(CGFloat)maxWidth font:(NSFont *)font {
NSDictionary *attrs = @{ NSFontAttributeName: font };
NSSize size = [self sizeWithAttributes:attrs];
if (size.width <= maxWidth)
return self;
NSMutableString *mutable = [self mutableCopy];
NSMutableString *mutableWithEllipsis = nil;
while (size.width > maxWidth) {
NSUInteger length = [mutable length];
NSUInteger middleIndex = length / 2;
NSRange composedCharacterRange = [mutable rangeOfComposedCharacterSequenceAtIndex:middleIndex];
mutableWithEllipsis = [mutable mutableCopy];
[mutableWithEllipsis replaceCharactersInRange:composedCharacterRange withString:@"…"];
[mutable replaceCharactersInRange:composedCharacterRange withString:@""];
size = [mutableWithEllipsis sizeWithAttributes:attrs];
}
return mutableWithEllipsis;
}
@Wevah
Copy link
Author

Wevah commented Nov 27, 2013

Feels kind of dirty/inefficient.

@Wevah
Copy link
Author

Wevah commented Nov 27, 2013

I use this for menu item title truncation, so font will often be [NSFont menuFontOfSize:14.0].

@Wevah
Copy link
Author

Wevah commented Nov 28, 2013

Probably better if it was on NSAttributedString instead?

@Wevah
Copy link
Author

Wevah commented Nov 29, 2013

Actually, that's slower. Using a layout manager might help immensely, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment