yibuyiqu yibuyiqu - 4 years ago 173
iOS Question

UILabel with mutiple lines to truncate one long word

I have a

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
, it always break the word into two lines. Like this:
I would like to truncate it in the first line, like this:

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

Answer Source

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.


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download