Last active
December 29, 2015 14:29
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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; | |
} |
I use this for menu item title truncation, so font
will often be [NSFont menuFontOfSize:14.0]
.
Probably better if it was on NSAttributedString instead?
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
Feels kind of dirty/inefficient.