Skip to content

Instantly share code, notes, and snippets.

@gotomanners
Created January 3, 2014 01:43
Show Gist options
  • Save gotomanners/8231078 to your computer and use it in GitHub Desktop.
Save gotomanners/8231078 to your computer and use it in GitHub Desktop.
@interface NSString (TruncateToWidth)
- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font;
@end
#import "NSString+TruncateToWidth.h"
#define ellipsis @"…"
@implementation NSString (TruncateToWidth)
- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font
{
// Create copy that will be the returned result
NSMutableString *truncatedString = [[self mutableCopy] autorelease];
// Make sure string is longer than requested width
if ([self sizeWithFont:font].width > width)
{
// Accommodate for ellipsis we'll tack on the end
width -= [ellipsis sizeWithFont:font].width;
// Get range for last character in string
NSRange range = {truncatedString.length - 1, 1};
// Loop, deleting characters until string fits within width
while ([truncatedString sizeWithFont:font].width > width)
{
// Delete character at end
[truncatedString deleteCharactersInRange:range];
// Move back another character
range.location--;
}
// Append ellipsis
[truncatedString replaceCharactersInRange:range withString:ellipsis];
}
return truncatedString;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment