33
votes

When I dynamically change the text of a UILabel I would prefer to get an ellipsis (dot, dot, dot) rather then have the text be automatically resized. How does one do this?

In other words, if I have UILabel with the word Cat with size font 14 and then I change the word to Hippopotamus the font shrinks to fit all the word. I would rather the word be automatically truncated followed by an ellipsis.

I assume there is a parameter that can be changed within my UILabel object. I'd rather not do this programmatically.

4

4 Answers

94
votes

Set the following properties:

Objective C

label.adjustsFontSizeToFitWidth = NO;
label.lineBreakMode = NSLineBreakByTruncatingTail;

Swift

label.adjustsFontSizeToFitWidth = false
label.lineBreakMode = .byTruncatingTail

You can also set these properties in interface builder.

13
votes

Swift solution:

label.lineBreakMode = .ByTruncatingTail

Swift 3:

label.lineBreakMode = .byTruncatingTail
10
votes

I had an issue producing ellipsis after I styled a UILabel and needed to use UILabel.attributedText instead of UILabel.text. There is a line break mode on the paragraph style that will overwrite the UILabel.lineBreakMode when using attributed text. You'll need to set the lineBreakMode to .byTruncatingTail on the attributed string's paragraph style if you want to achieve ellipsis.

e.g.

    let text = "example long string that should be truncated"
    let attributedText = NSMutableAttributedString(
        string: text, 
        attributes: [.backgroundColor : UIColor.blue.cgColor]
    )
    let range = NSRange(location: 0, length: attributedText.length)
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineBreakMode = .byTruncatingTail
    attributedText.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
    uiLabel.attributedText = attributedText
0
votes

In the interface builder this is the way to go:

Line Break setting in Interface Builder