Getting UILabel to produce an ellipsis rather than shrinking the font Getting UILabel to produce an ellipsis rather than shrinking the font xcode xcode

Getting UILabel to produce an ellipsis rather than shrinking the font


Set the following properties:

Objective C

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

Swift

label.adjustsFontSizeToFitWidth = falselabel.lineBreakMode = .byTruncatingTail

You can also set these properties in interface builder.


Swift solution:

label.lineBreakMode = .ByTruncatingTail

Swift 3:

label.lineBreakMode = .byTruncatingTail


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