Truncate String Adding Ellipsis At Front, Middle Or End

Using attributed strings you can easily truncate strings, adding ellipsis at the front, middle or end.

For example, let’s say you have the string: @”May you always have a cellar full of beer.” and want to display this within a label, having the string truncated as needed to fit. Using an NSMutableParagraphStyle and adding this to an attributed string you can create output that looks as follows:


The code below shows how to create a NSMutableAttributedString and a NSMutableParagraphStyle, setting the preferred line truncation by tweaking the code in lines 10-12:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//-----------------------------
// Create attributed string
//-----------------------------
NSString *str = @"May you always have a cellar full of beer.";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
 
// Create NSMutableParagraphStyle object
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
[paragraph setAlignment:NSTextAlignmentCenter];
[paragraph setAlignment:NSLineBreakByTruncatingHead];
//  [paragraph setAlignment:NSLineBreakByTruncatingTail];
//  paragraph.lineBreakMode = NSLineBreakByTruncatingMiddle;
 
// Add attribute NSParagraphStyleAttributeName
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, [attributedString length])];
 
// Set background color for entire range
[attributedString addAttribute:NSBackgroundColorAttributeName
  value:[UIColor colorWithRed:0.103 green:0.305 blue:0.492 alpha:1.000]
  range:NSMakeRange(0, [attributedString length])];
 
// Define label
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 20, 269, 40)];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setTextColor:[UIColor colorWithRed:0.998 green:0.985 blue:0.307 alpha:1.000]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextAlignment:UITextAlignmentLeft];
 
// Set label text to attributed string
[label setAttributedText:attributedString];
[[self view] addSubview:label];
More On NSMutableAttributedString

You can read more about attributed strings here:

Set Text Font, Foreground And Background Colors, StrikeThrough And Shadow – Part 1
Set Text Underline, Paragraph Styles and Glyph Form – Part 2