Posted By

rabc on 07/26/10


Tagged

String iphone nsstring


Versions (?)

Truncate a String


 / Published in: Objective C
 

URL: http://iphonedevelopertips.com/cocoa/truncate-an-nsstring-and-append-an-ellipsis-respecting-the-font-size.html

  1. #import "NSString+TruncateToWidth.h"
  2.  
  3. #define ellipsis @"�¢ï¿½�¦"
  4.  
  5. @implementation NSString (TruncateToWidth)
  6.  
  7. - (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font
  8. {
  9. // Create a copy that will be truncated and returned
  10. NSMutableString *truncatedString = [[self mutableCopy] autorelease];
  11.  
  12. // Accommodate for ellipsis we'll tack on the end
  13. width -= [ellipsis sizeWithFont:font].width;
  14.  
  15. // Get range for last character in string
  16. NSRange range = {truncatedString.length - 1, 1};
  17.  
  18. // Loop, deleting characters until string fits within width
  19. while ([truncatedString sizeWithFont:font].width > width)
  20. {
  21. // Delete character at end
  22. [truncatedString deleteCharactersInRange:range];
  23.  
  24. // Move back another character
  25. range.location--;
  26. }
  27.  
  28. // Append ellipsis
  29. [truncatedString replaceCharactersInRange:range withString:ellipsis];
  30.  
  31. return truncatedString;
  32. }
  33.  
  34. @end

Report this snippet  

You need to login to post a comment.