forked from piersoft/Acqualta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSString+TruncateToWidth.m
executable file
·43 lines (31 loc) · 1.25 KB
/
NSString+TruncateToWidth.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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 sizeWithAttributes:@{NSFontAttributeName:font}].width > width)
if ([self sizeWithFont:font].width > width)
{
// Accommodate for ellipsis we'll tack on the end
// width -= [ellipsis sizeWithAttributes:@{NSFontAttributeName:font}].width;
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 sizeWithAttributes:@{NSFontAttributeName:font}].width > 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