Uilabel Text Truncation VS. Line Breaks in Text

.ByTruncatingHead works the way truncatingmiddle should have when numberoflines is 0 for UILabel

The rule is that with a truncating policy, a UILabel breaks the text at word-end, and then, if the text is too long for the label, the last line displays an ellipsis at the start, middle, or end of the line respectively, and text is omitted at the point of the ellipsis.

So in fact your code does not behave the same way as byTruncatingMiddle, which puts the ellipses in the middle of the last line. Your code puts the ellipses at the start of the last line.

UILabel with mutiple lines to truncate one long word

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

UILabel truncate tail and skip not complete word

You can do something like this:

let labelWidth = CGRectGetWidth(label.bounds)

let str = "You will have 30 seconds till you give us a good impression" as NSString
let words = str.componentsSeparatedByString(" ")

var newStr = "" as NSString

for word in words{

let statement = "\(newStr) \(word) ..." as NSString
let size = statement.sizeWithAttributes([NSFontAttributeName:label.font])
if size.width < labelWidth {
newStr = "\(newStr) \(word)"
}
else{
break
}
}

newStr = newStr.stringByAppendingString(" ...")

self.label.text = newStr as String

Idea is: we split words and try check the width while appending from the beginning + the string "..." till we found the a word that will exceed the size, in the case we stop and use this new string

UILabel truncate even when it has remaining lines

Use another line breaking mode.

[_detailedTextLabel setLineBreakMode:NSLineBreakByWordWrapping];

and also ensure that label has proper height (given that width is already set):

CGSize size = [_detailedTextLabel sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)];
_detailedTextLabel.frame = CGRectMake(0, 0, size.width, size.height);


Related Topics



Leave a reply



Submit