Created
January 3, 2014 01:43
-
-
Save gotomanners/8231078 to your computer and use it in GitHub Desktop.
Truncate a String and Append an Ellipsis, Respecting the Font Size http://iosdevelopertips.com/cocoa/truncate-an-nsstring-and-append-an-ellipsis-respecting-the-font-size.html
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
@interface NSString (TruncateToWidth) | |
- (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font; | |
@end |
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
#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