How to crop NSString based on graphic width?

UILabel has a label truncation function using various truncation methods (UILineBreakMode). NSString UIKit Additions has similar functionality for drawing strings.

However, I did not find access to the actual truncated string. Is there any other way to get a truncated string based on (graphic) width for a given font?

I would like to have a category in NSString using this method:

-(NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode 
+6
ios objective-c iphone cocoa-touch nsstring
source share
2 answers

One option tries to loop in different sizes until you get the right width. That is, start with a full line, if it is wider than you need, replace the last two characters with an ellipsis. Loop until it gets narrow enough.

If you think you will work with long strings, you can binary search your path to the truncation point to make it a little faster.

+6
source share
 - (NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode { NSMutableString *resultString = [[self mutableCopy] autorelease]; NSRange range = {resultString.length-1, 1}; while ([resultString boundingRectWithSize:CGSizeMake(FLT_MAX, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.width > width) { // delete the last character [resultString deleteCharactersInRange:range]; range.location--; // replace the last but one character with an ellipsis [resultString replaceCharactersInRange:range withString:truncateReplacementString]; } return resultString; } 

Please note that with iOS 6, this method is not safe to run in the background thread.

+17
source share

All Articles