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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With