123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- #import "NSString+TruncateToWidth.h"
- #define ellipsis @"…"
- @implementation NSString (TruncateToWidth)
- - (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font atEnd:(BOOL)atEnd
- {
-
- NSMutableString *truncatedString = [self mutableCopy];
-
-
- if ([self widthWithFont:font] > width)
- {
-
- width -= [ellipsis widthWithFont:font];
-
-
- while ([truncatedString widthWithFont:font] > width)
- {
- NSRange range;
-
- if (atEnd) {
- range.location = [truncatedString length] -1;
- range.length = 1;
- }else {
- range.location = 0;
- range.length = 1;
- }
-
-
- [truncatedString deleteCharactersInRange:range];
- }
-
-
- if (atEnd) truncatedString = (NSMutableString *)[truncatedString stringByAppendingString:ellipsis];
- else [truncatedString replaceCharactersInRange:NSMakeRange(0, 0) withString:ellipsis];
- }
-
- return truncatedString;
- }
- - (CGFloat)widthWithFont:(UIFont *)font
- {
- return [self sizeWithAttributes:@{NSFontAttributeName:font}].width;
- }
- @end
|