Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a string and add ellipsis at the end in Objective-c

How to truncate a string in Objective-C and then add the ellipsis at the end?

like image 247
Suchi Avatar asked Jul 19 '11 20:07

Suchi


2 Answers

In case you wish to truncate and add ellipsis to a string with the maximum being a specific width, here is an implementation that takes into account font and size:

+ (NSString *)stringByTruncatingString: (NSString *)string toWidth: (CGFloat)width withFont: (UIFont *)font
{
    #define ellipsis @"..."
    NSMutableString *truncatedString = [string mutableCopy];

    if ([string sizeWithAttributes: @{NSFontAttributeName: font}].width > width) {
        width -= [ellipsis sizeWithAttributes: @{NSFontAttributeName: font}].width;

        NSRange range = {truncatedString.length - 1, 1};

        while ([truncatedString sizeWithAttributes: @{NSFontAttributeName: font}].width > width) {
            [truncatedString deleteCharactersInRange:range];
            range.location--;
        }

        [truncatedString replaceCharactersInRange:range withString:ellipsis];
    }

    return truncatedString;
}
like image 67
Tonithy Avatar answered Sep 20 '22 11:09

Tonithy


I wrote simple category to truncate NSString by words:

@interface NSString (TFDString)

- (NSString *)truncateByWordWithLimit:(NSInteger)limit;


@end


@implementation NSString (TFDString)

- (NSString *)truncateByWordWithLimit:(NSInteger)limit {
    NSRange r = NSMakeRange(0, self.length);
    while (r.length > limit) {
        NSRange r0 = [self rangeOfString:@" " options:NSBackwardsSearch range:r];
        if (!r0.length) break;
        r = NSMakeRange(0, r0.location);
    }
    if (r.length == self.length) return self;
    return [[self substringWithRange:r] stringByAppendingString:@"..."];
}


@end

Usage:

NSString *xx = @"This string is too long, somebody just need to take and truncate it, but by word, please.";
xx = [xx truncateByWordWithLimit:50];

Result:

This string is too long, somebody just need to...

Hope it helps somebody.

like image 22
Mike Keskinov Avatar answered Sep 19 '22 11:09

Mike Keskinov