Published

Truncate a String and Append an Ellipsis, Respecting the Font Size

A number of the UI related controls will automatically truncate and append ellipsis with no effort required on your part. For example, with UILabel you can specify the linebreak mode to indicate how you would like the system to manage wrapping and truncating the label text.

However, they are times when having a method to truncate a string without using a UI control would be handy. In this post I’ll create a category which will add a method to the NSString class to do just that. You can read more about working with categories in this post: Introduction to Categories.

NSString Category

Start by creating a new interface file with the name: NSString+TruncateToWidth.h – appending the method name to the class is a common naming convention when working with categories.

The code below defines a method that will be available to all NSString objects. The method will truncate a string to a specific width, using the font size to properly determine the string size before truncating:

Notice that the desired final width of the string is passed in, as well as the font that will be used when calculating the size (width) of the string. The process is quite simple: change the incoming width to accommodate an ellipsis on the end of the string – loop through the string removing characters from the end until the desired width is reached – append an ellipsis onto the string.

Calling the Truncate NSString Method

You can now call the method stringByTruncatingToWidth:withFont: on any NSString object:

Hello. Thank you for that. Is there any way to truncate multiline text? I mean adding to your category method like – (NSString*)stringByTruncatingToSize:(CGSize)size withFont:(UIFont *)font; Is it possible?
Thanks in advance.

Thank you for the post, it helped me fit long descriptions into back buttons for a custom titleView.

I found however that it was very inefficient in these circumstances, so I decided to add the caveat that if the width of the original string is twice the length of the desired length, it should go from the other end.

Have tested this code and it seems to work well:

– (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font
{
// Create copy that will be the returned result
NSMutableString *truncatedString = [self mutableCopy];

// Make sure string is longer than twice requested width, then approach truncation from Right hand Side
// Else if string is long than width but not twice, approach truncation from Left hand side.
if ([self sizeWithFont:font].width > 2*width) {
// Accommodate for ellipsis we’ll tack on the end
width -= [ellipsis sizeWithFont:font].width;

// Create new string as we are coming from the other end!
truncatedString = [NSMutableString string];

// We need the range of the first character in string
NSRange range = {0, 1};