Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel with mutiple lines to truncate one long word

Tags:

ios

iphone

I have a UIlabel view which allow to show two lines of strings. But in my case, there is one long word only. Whatever I set the line break mode to UILineBreakModeTailTruncation or UILineBreakModeWordWrap, it always break the word into two lines. Like this: "xxxxxx xx" I would like to truncate it in the first line, like this: "xxxx..."

Is there any way to implement that. In most of the cases, it should allow to show two lines of words.

Additional edit: Take following image as an example. The top two labels are what I expected: one long word can be truncated in one line; multiple short words can be show in two lines. The bottom label is currently happened.

enter image description here

like image 549
yibuyiqu Avatar asked Jul 05 '12 06:07

yibuyiqu


1 Answers

In order to do what you're asking you need to find out if there is only one word. If there is, set the number of lines to 1 and the auto-shrink should fix things. If there is not, then set the number of lines to 0.

e.g.

UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:12.0];
label.adjustsFontSizeToFitWidth = YES;
label.minimumScaleFactor = 0.8;
label.text = NSLocalizedString(@"Information", @"E: 'Information'");
NSUInteger words = [label.text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].count;
label.numberOfLines = (words == 1) ? 1 : 0;

Swift 3.0

let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.8
label.text = NSLocalizedString("Information", comment: "E: 'Information'")
let words = label.text?.components(separatedBy: NSCharacterSet.whitespacesAndNewlines).count
label.numberOfLines = words == 1 ? 1 : 0
like image 142
MJLyco Avatar answered Nov 14 '22 22:11

MJLyco