Truncate part of text in UILabel

Viewed 37243

My requirement is that I need to display text in label in such a way that if the length of text is too big to accommodate in one line, i need to truncate it at the end in such a way that only the last few characters(usually a number b/w 1-1000 so text length may vary.) are visible and the text before it is truncated with "...".

So the text will look something like "abcdefgijk...10"

Is there any way I can achieve this?

10 Answers

Try this:

 label.lineBreakMode = NSLineBreakByTruncatingMiddle;

UILineBreakModeMiddleTruncation is deprecated from iOS 6.0.

there are many methods in NSString class use -length and then use any of these

– substringFromIndex:
– substringWithRange:
– substringToIndex:

create a temporary string using NSString stringwithFormat, put your desired charecters you get from substringTo index and "....." then your numbers from string by substringFromIndex.

hope this helps

You can start with finding the length of characters that can be placed in a line, say 'n' characters. You can take help of this link to determine 'n' How to know if NSString fits in UILabel or not and index of the last string which fits?. Next, find the length of the string. If it exceeds n, then extract the last two characters. Ex

NSString * fooString = @"a very long string";
NSString * s2 = [fooString substringWithRange:NSMakeRange([fooString length]-3, 2)];
NSString * s1 = [fooString substringWithRange:NSMakeRange(0 , n-5)];
NSString * newString = [NSString stringWithFormat:@"%@...%@",s1,s2];

We have different Line Break modes for UILabel like

Truncate Head, Truncate Middle, Truncate Tail

In Xib you can set the Line Break mode what ever you want

If you using XIB file..

select --> UILable and select --> Attribute inspector tag and change into Line Breaks-->Truncate tail

simply way to truncate characters...

Here is how to use it, NSLineBreakByTruncatingMiddle

UILabel *temp = [[UILabel alloc]initWithFrame:CGRectMake(5,75, 100, 50)];
[temp setBackgroundColor:[UIColor lightGrayColor]];
temp.lineBreakMode = NSLineBreakByTruncatingMiddle;
temp.text = @"HelloBoss997";

Output : Hello...s997

Related