Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate part of text in UILabel

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?

like image 319
user2990765 Avatar asked Dec 06 '13 06:12

user2990765


People also ask

How do you truncate text in Swift?

string-truncate.swift Truncates the string to the specified length number of characters and appends an optional trailing string if longer. - Parameter trailing: A 'String' that will be appended after the truncation. - Returns: 'String' object. let str = "I might be just a little bit too long".

How do you wrap text in UILabel?

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed. If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option + return to get a line break - return alone will finish editing.


2 Answers

UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(50,100, 150, 30)];
contentLabel.text = @"abcdefghijklmnopqrstuvwxyz10";
contentLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;

Add this label to your display. You should get a output something like this

abcdefghijklmnopq...10
like image 72
Srinivasan N Avatar answered Oct 07 '22 15:10

Srinivasan N


For everyone looking for more recent solution, swift 3 :

yourLabel.lineBreakMode = .byTruncatingMiddle;
like image 39
Melanie Journe Avatar answered Oct 07 '22 15:10

Melanie Journe